【问题标题】:How to put an array of strings with two variables into a text file?如何将具有两个变量的字符串数组放入文本文件中?
【发布时间】:2020-03-08 12:55:58
【问题描述】:

我正在尝试制作一个文本分类器应用程序。我有一个字符串数组,其中包含两个用逗号分隔的参数,如下所示:

pos_tweets = [('I love this car', 'positive'),
              ('This view is amazing', 'positive'),
              ('I feel great this morning', 'positive')]

我可以使用该字符串数组执行以下代码:

tweets = []
for (words, sentiment) in pos_tweets:
    words_filtered = [e.lower() for e in words.split() if len(e) >= 3] 
    tweets.append((words_filtered, sentiment))
print(tweets)

带输出:

[(['love', 'this', 'car'], 'positive'), (['this', 'view', 'amazing'], 'positive'), (['feel', 'great', 'this', 'morning'], 'positive')]

我想要做的是将该字符串数组放入一个文本文件中,并且仍然能够以与上面相同的输出执行代码。

【问题讨论】:

  • 请分享您迄今为止尝试写入文本文件的步骤,并指定您需要帮助的部分。如果您正在寻找“如何在 python 中将文本写入文件”这个问题的答案,我建议您看看其他类似这样的问题:stackoverflow.com/questions/31499257/…

标签: python arrays python-3.x text-classification naivebayes


【解决方案1】:

要将列表输出到 txt 文件,可以使用 pickle 模块

我看不出如何在从 txt 文件中读取后获得相同的输出,但您可以通过对当前代码进行非常小的修改来做到这一点。

要将列表输出到文本文件,您可以:

with open('outfile', 'wb') as fp:
    pickle.dump(tweets, fp)

要从中读取,您可以这样做:

with open('outfile', 'rb') as fp:
    pos_tweets = pickle.load(fp)

for (words, sentiment) in pos_tweets:
    if type(words) == list:
        words = ' '.join(words)
    words_filtered = [e.lower() for e in words.split() if len(e) >= 3]
    tweets.append((words_filtered, sentiment))

通过将上述修改后的代码迭代到 pos_tweets,您可以使用硬编码的推文或从 txt 文件中读取的推文。

完整代码如下:

import pickle

pos_tweets = [('I love this car', 'positive'),
              ('This view is amazing', 'positive'),
              ('I feel great this morning', 'positive')]


def get_tweets(p_tweets):
    tweets = []
    for (words, sentiment) in p_tweets:
        if type(words) == list:
            words = ' '.join(words)
        words_filtered = [e.lower() for e in words.split() if len(e) >= 3]
        tweets.append((words_filtered, sentiment))
    return tweets


t = get_tweets(pos_tweets)

print(t)
with open('outfile', 'wb') as fp:
    pickle.dump(t, fp)

with open('outfile', 'rb') as fp:
    pos_tweets = pickle.load(fp)

t = get_tweets(pos_tweets)
print(t)

【讨论】:

    【解决方案2】:

    您可以有一个文本文件,其中每一行都包含 pos_tweets 数组中的一个元素。所以在

    pos_tweets.txt

    I love this car, positive
    This view is amazing, positive
    

    然后你可以阅读每一行

    import csv
    
    tweets = []
    with open('pos_tweets.txt') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            words = row[0]
            sentiment = row[1]
            words_filtered = [e.lower() for e in words.split() if len(e) >= 3] 
            tweets.append((words_filtered, sentiment))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 2021-04-16
      • 2011-01-13
      • 2020-05-31
      • 2012-05-05
      • 1970-01-01
      • 2011-07-23
      相关资源
      最近更新 更多