2016-04-12 20 views
0

我想寫一個代碼在情感分析領域。我有一個字典(.txt),其中的字是評級,例如「好,2」和「壞,-3」。現在我想讓Python在一個給定的句子中統計正面和負面。我的代碼片段看起來是這樣的:追加函數for循環不起作用

text ='' 

result = [] 
for sentence in sent_tokenize(text): 
    pos = 0 
    neg = 0 
    for word in word_tokenize(sentence): 
     score = Dictionary.get(word, 0) 
     if score > 0: 
      pos += score 
      if score < 0: 
       neg += score 
       result.append([pos, neg]) 

for s in result: print(s) 

print(result) 

所以我想要的結果看起來是這樣的:[5, -6]。 但我得到一個空的結果:[]。 你知道我在做什麼錯嗎?

+0

你在哪裏定義'sent_tokenize()'和'word_tokenize()'? – zondo

+0

早先在代碼中,我定義了它:句子= word_tokenize(''。lower())和句子= sent_tokenize(''。lower()) – Tommy5

+0

這就是調用函數,而不是定義它們。 – zondo

回答

2

score不能在同一時間少和大於零:

if score > 0: 
    pos += score 
    if score < 0: 
     neg += score 
     result.append([pos, neg]) 

你的代碼更改爲:

result = [] 
for sentence in sent_tokenize(text): 
    pos = 0 
    neg = 0 
    for word in word_tokenize(sentence): 
     score = Dictionary.get(word, 0) 
     if score > 0: 
      pos += score 
     if score < 0: 
      neg += score 
    result.append([pos, neg]) 

result.append([pos, neg])的縮進。這應該會給你一個新的 對每個句子pos, neg

+0

感謝您的建議!不幸的是,我仍然得到一個空的輸出...我必須改變其他的東西嗎? – Tommy5

+0

只需添加一些調試打印以查看「句子」和「詞」具有的值。確保你真的做循環。 ;) –

+0

你得到它的工作? –