如何正确循环两个文件,将两个文件中的字符串相互比较

时间:2013-05-06 04:04:46

标签: python loops file-io

我无法针对单词列表(文件2,制表符分隔,两列)对其分配的情绪(正面或负面)进行推文(文件1,标准twitter json响应)的情绪分析。

问题是:顶部循环只运行一次然后脚本结束,而我循环遍历文件1然后嵌套在我循环文件2并尝试比较并保持合并情绪的运行总和每条推文。

所以我有:

def get_sentiments(tweet_file, sentiment_file):


    sent_score = 0
    for line in tweet_file:

        document = json.loads(line)
        tweets = document.get('text')

        if tweets != None:
            tweet = str(tweets.encode('utf-8'))

            #print tweet


            for z in sentiment_file:
                line = z.split('\t')
                word = line[0].strip()
                score = int(line[1].rstrip('\n').strip())

                #print score



                if word in tweet:
                    print "+++++++++++++++++++++++++++++++++++++++"
                    print word, tweet
                    sent_score += score



            print "====", sent_score, "====="

    #PROBLEM, IT'S ONLY DOING THIS FOR THE FIRST TWEET

file1 = open(tweetsfile.txt)
file2 = open(sentimentfile.txt)


get_sentiments(file1, file2)

我花了半天时间试图找出为什么它打印出所有推文而没有为file2嵌套for循环,但是有了它,它只处理第一条推文然后退出。

1 个答案:

答案 0 :(得分:3)

它只执行一次的原因是for循环已经到达文件的末尾,所以它停止了,因为没有更多的行要读取。

换句话说,第一次循环运行时,它会逐步遍历整个文件,然后由于没有更多行要读取(因为它到达文件的末尾),它不再循环,结果只处理一行。

因此解决此问题的一种方法是“回放”文件,您可以使用文件对象的seek方法执行此操作。

如果您的文件不大,另一种方法是将它们全部读入列表或类似结构,然后循环遍历它。

然而,由于您的情绪评分是一个简单的查找,最好的方法是建立一个带有情绪分数的字典,然后查找字典中的每个单词来计算推文的整体情绪:

import csv
import json

scores = {}  # empty dictionary to store scores for each word

with open('sentimentfile.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        scores[row[0].strip()] = int(row[1].strip()) 


with open('tweetsfile.txt') as f:
    for line in f:
        tweet = json.loads(line)
        text = tweet.get('text','').encode('utf-8')
        if text:
            total_sentiment = sum(scores.get(word,0) for word in text.split())
            print("{}: {}".format(text,score))

with statement会自动关闭文件处理程序。我使用csv module来读取文件(它也适用于制表符分隔文件)。

此行进行计算:

total_sentiment = sum(scores.get(word,0) for word in text.split())

编写此循环是一种较短的方法:

tweet_score = []
for word in text.split():
    if word in scores:
        tweet_score[word] = scores[word]

total_score = sum(tweet_score)

get字典方法接受第二个可选参数,以便在找不到密钥时返回自定义值;如果省略第二个参数,它将返回None。在我的循环中,如果单词没有分数,我会使用它返回0。