2014-03-31 38 views
0

我试图在Python中创建一个情感分析器,它下载文本并根据负面和正面的单词列表进行分析。对于文本内每一个匹配的文字,在poswords.txt应该有一个+1得分和文本内的每一个匹配negwords.txt应该有一个-1得分,文本的总体得分将是情绪评分。这是我试图做到这一点,但我一直在刚开评价为0。将下载的字符串与Python中的列表进行比较

下面的答案似乎不工作,我不断收到的0

​​

回答

1

poswords景气指数和你的代码中的negwords只是文件句柄,你不会读这些文件中的单词。

这里:

split = text.split() 
poswords = open('poswords.txt','r') 
pos = [] 
for line in poswords: 
    pos.append(line.strip()) 
for word in split: 
    if word in pos: 
     sentimentScore +=1 
poswords.close() 

negwords = open('negwords.txt','r') 
neg = [] 
for line in negwords: 
    neg.append(line.strip()) 
for word in split: 
    if word in neg: 
     sentimentScore -=1 
negwords.close() 

如果文件是巨大的,上面的是不是一个最佳的解决方案。创建字典正反字:

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

嗨Warunsl,感谢您的快速回复,然而,这段代码似乎没有工作,我仍然在所有的“INPUT_TEXT”得到的0景气指数我正在通过分析仪 – user3482449

相关问题