[英]how to properly loop through two files comparing strings in both files against each other
我在对单词列表(文件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)
我花了更好的一天时间来弄清楚为什么它会打印出所有tweet,而没有为file2嵌套嵌套的for循环,但是有了它,它只会处理第一个tweet,然后退出。
它只执行一次的原因是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
模块读取文件(它也适用于制表符分隔的文件)。
这行进行计算:
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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.