【发布时间】:2013-12-30 18:07:49
【问题描述】:
我正在对一个句子进行逐字分析,例如
“嘿嘿!!这是一部很棒的电影???”
我有很多像上面这样的句子。
我有一个巨大的数据集文件,如下所示,如果该单词存在,我必须快速查找。如果确实如此,则进行分析并存储在字典中,例如从单词的文件中获取分数,句子最后一个单词的分数,句子的第一个单词等等。
sentence[i] => 嘿嘿!!这是一部优秀的电影??? 句子[0] =嘿,句子[1]=那里!! sentence[2]=这个等等。
代码如下:
def unigrams_nrc(file):
for line in file:
(term,score,numPos,numNeg) = re.split("\t", line.strip())
if re.match(sentence[i],term.lower()):
#presence or absence of unigrams of a target term
wordanalysis["unigram"] = found
else:
found = False
if found:
wordanalysis["trail_unigram"] = found if re.match(sentence[(len(sentence)-1)],term.lower()) else not(found)
wordanalysis["lead_unigram"] = found if re.match(sentence[0],term.lower()) else not(found)
wordanalysis["nonzero_sscore"] = float(score) if (float(score) != 0) else 0
wordanalysis["sscore>0"] = (float(score) > 0)
wordanalysis["sscore"] = (float(score) != 0)
if re.match(tweet[len(sentence)-1],term.lower()):
wordanalysis["sscore !=0 last token"] = (float(score) != 0)
这是文件(这个文件超过4000字):
#fabulous 7.526 2301 2
#excellent 7.247 2612 3
#superb 7.199 1660 2
#perfection 7.099 3004 4
#terrific 6.922 629 1
#magnificent 6.672 490 1
#sensational 6.529 849 2
#heavenly 6.484 2841 7
#ideal 6.461 3172 8
#partytime 6.111 559 2
#excellence 5.875 1325 6
@thisisangel 5.858 217 1
#wonderful 5.727 3428 18
elegant 5.665 537 3
#perfect 5.572 3749 23
#fine 5.423 2389 17
excellence 5.416 279 2
#realestate 5.214 114 1
bicycles 5.205 113 1
我想知道是否有更好的方法来完成上述操作? 定义更好的方式:更快、更少代码、更优雅。 我是 python 新手,所以我知道这不是最好的代码。我有大约 4 个文件,我必须通过这些文件检查分数,因此希望以最好的方式实现此功能。
【问题讨论】:
-
定义“更好的方式”?更快、更少代码、更优雅?看起来你的解决方案写得很好。我认为它有效?
-
我可以建议将文件存储为 JSON,这样您就可以简单地
json.laods(data)数据文件。 -
@JamesMills 更好的方法是更快、更少代码和更优雅。我的解决方案运行良好,但我正在寻找是否有更好的方法。
-
@JamesMills 将文件存储为 json 有什么好处?
-
另一种编码风格的注释——你不需要写
sentence[(len(sentence)-1)]来获取列表的最后一个元素,你可以写sentence[-1]。
标签: python regex dictionary word sentiment-analysis