我正在对一个句子进行逐字分析,例如
“嘿,那里!!这是一部很棒的电影
我有很多类似的句子。
我有一个巨大的数据集文件,如下所示,我必须做一个快速查找,如果这个词存在。如果它真的这样做了分析和存储在字典里,比如从单词的文件中得到分数,句子最后一个单词的分数,句子的第一个单词等等。
句子[i]=>;嘿,那里!!这是一部很棒的电影??? 句子[0]=嘿,句子[1]=那里!!句子[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字):
^{pr2}$我想知道有没有更好的方法来完成上面的工作? 定义更好的方式:更快,更少的代码和优雅。 我是python新手,所以我知道这不是最好的代码。我有大约4个文件,我必须去检查分数,因此我想实现这个功能在最好的可能的方式。在
也许将单词/分数文件作为dict的dict加载到内存中,然后循环遍历每个句子中的每个单词,检查单词文件中句子中每个单词的dict键。在
像这样的东西能起作用吗:
以下是我的建议:
json.dumps()
将文件写成JSONjson.laods()
将文件作为JSON加载对于复杂度为O(1)的查找,Python
dict
(s)要比具有O(n)的迭代快得多,因此只要您最初加载数据文件,就可以获得一些性能优势。在示例:
我可能会这样存储你的数据:
^{pr2}$然后你会:
NB:这些
...
是不是实际代码和占位符,您应该在这些地方填充空格。在相关问题 更多 >
编程相关推荐