将下载的字符串与Python中的列表进行比较
我正在尝试用Python创建一个情绪分析器,它下载文本,并根据一系列消极和积极的词语对其进行分析。对于文本中与poswords.txt中的一个单词的每一个匹配,都应该有一个将下载的字符串与Python中的列表进行比较,python,comparison,analysis,Python,Comparison,Analysis,我正在尝试用Python创建一个情绪分析器,它下载文本,并根据一系列消极和积极的词语对其进行分析。对于文本中与poswords.txt中的一个单词的每一个匹配,都应该有一个+1分数;对于文本中与negwords.txt中的每一个匹配,都应该有一个-1分数,文本的总分数将是情绪分数。这就是我试图做到的,但我一直只得到0分 split = text.split() poswords = open('poswords.txt','r') for word in split:
+1
分数;对于文本中与negwords.txt中的每一个匹配,都应该有一个-1
分数,文本的总分数将是情绪分数。这就是我试图做到的,但我一直只得到0分
split = text.split()
poswords = open('poswords.txt','r')
for word in split:
if word in poswords:
sentimentScore +=1
poswords.close()
negwords = open('negwords.txt','r')
for word in split:
if word in negwords:
sentimentScore -=1
negwords.close()
下面的答案似乎不起作用,我的情绪得分一直是0
split = text.split()
poswords = open('poswords.txt','r')
for word in split:
if word in poswords:
sentimentScore +=1
poswords.close()
negwords = open('negwords.txt','r')
for word in split:
if word in negwords:
sentimentScore -=1
negwords.close()
代码中的
poswords
和negwords
只是文件句柄,您没有读取这些文件中的单词
在这里:
如果文件很大,上述方法不是最佳解决方案。为肯定词和否定词创建词典:
input_text = text.split() # avoid using split as a variable name, since it is a keyword
poswords = open('poswords.txt','r')
pos_dict = defaultdict(int)
for line in poswords:
pos_dict[line.strip()] += 1
poswords.close()
negwords = open('negwords.txt','r')
neg_dict = defaultdict(int)
for line in negwords:
neg_dict[line.strip()] += 1
negwords.close()
sentiment_score = 0
for word in input_text:
if word in pos_dict:
sentiment_score += 1
elif word in neg_dict:
sentiment_score -=1
您好,沃伦,谢谢您的快速回复,但是,此代码似乎不起作用,我通过分析仪传递的所有“输入文本”的情绪得分仍然为0