簡體   English   中英

區別詞情感分析

[英]Distinct words sentiment analysis

我嘗試根據7000個單詞的字典進行情感分析。 該代碼在Python中有效,但是它選擇所有組合而不是不同的單詞。

例如,詞典說enter ,文本說enterprise 如何更改將其視為不匹配的代碼?

dictfile = sys.argv[1]
textfile = sys.argv[2]

a = open(textfile)
text = string.split( a.read() )
a.close()

a = open(dictfile)
lines = a.readlines()
a.close()

dic = {}
scores = {}

current_category = "Default"
scores[current_category] = 0

for line in lines:
   if line[0:2] == '>>':
       current_category = string.strip( line[2:] )
       scores[current_category] = 0
   else:
       line = line.strip()
       if len(line) > 0:
           pattern = re.compile(line, re.IGNORECASE)
           dic[pattern] = current_category

for token in text:
   for pattern in dic.keys():
       if pattern.match( token ):
           categ = dic[pattern]
           scores[categ] = scores[categ] + 1

for key in scores.keys():
   print key, ":", scores[key]

.match()從行首開始匹配。 因此,您可以在reg ex中使用行尾錨:

re.compile(line + '$')

或者您可以使用單詞邊界:

re.compile('\b' + line + '\b')
  1. 您的縮進不連貫。 某些級別使用3個空格,有些使用4個空格。

  2. 您嘗試將文本中的每個單詞與詞典中的所有7000個單詞進行匹配。 而是只是在字典中查找單詞。 如果不存在,請忽略該錯誤(EAFP原理)。

  3. 另外,我不確定使用類方法( string.split() )是否比對象方法( "".split() )有優勢。

  4. Python也有一個defaultdict ,它自己用0初始化字典。

編輯:

  1. 代替.readlines()我使用.read().split('\\n') 這擺脫了換行符。

  2. 我試圖消除標點符號的目的不是在默認的空格字符處而是在正則表達式'\\W+'不是 “單詞字符”的所有內容)上拆分文本。

在我建議的代碼下面:

import sys
from collections import defaultdict

dictfile = sys.argv[1]
textfile = sys.argv[2]

with open(textfile) as f:
    text = f.read()

with open(dictfile) as f:
    lines = f.read()

categories = {}
scores = defaultdict(int)

current_category = "Default"
scores[current_category] = 0

for line in lines.split('\n'):
    if line.startswith('>>'):
        current_category = line.strip('>')
    else:
        keyword = line.strip()
        if keyword:
            categories[keyword] = current_category

for word in re.split('\W+', text):
    try:
        scores[categories[word]] += 1
    except KeyError:
        # no in dictionary
        pass

for keyword in scores.keys():
    print("{}: {}".format(keyword, scores[keyword]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM