python文件中的单词分析和评分

2024-09-26 22:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在对一个句子进行逐字分析,例如
“嘿,那里!!这是一部很棒的电影

我有很多类似的句子。 我有一个巨大的数据集文件,如下所示,我必须做一个快速查找,如果这个词存在。如果它真的这样做了分析和存储在字典里,比如从单词的文件中得到分数,句子最后一个单词的分数,句子的第一个单词等等。

句子[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个文件,我必须去检查分数,因此我想实现这个功能在最好的可能的方式。在


Tags: 文件reifmatchfloat单词lowerelse
2条回答

也许将单词/分数文件作为dict的dict加载到内存中,然后循环遍历每个句子中的每个单词,检查单词文件中句子中每个单词的dict键。在

像这样的东西能起作用吗:

word_lookup = load_words(file)
for s in sentences:
    run_sentence(s)

def load_words(file):
    word_lookup = {}
    for line in file:
        (term,score,numPos,numNeg) = re.split("\t", line.strip())
        if not words.has_key(term):
            words[term] = {'score': score, 'numPos': numPos, 'numNeg': numNeg}
    return word_lookup

def run_sentence(s):
    s = standardize_sentence(s) # Assuming you want to strip punctuation, symbols, convert to lowercase, etc
    words = s.split(' ')
    first = words[0]
    last = words[-1]
    for word in words:
        word_info = check_word(word)
        if word_info:
            # Matched word, use your scores somehow (word_info['score'], etc)

def check_word(word):
    if word_lookup.has_key(word):
        return word_lookup[word]
    else:
        return None

以下是我的建议:

  • 使用json.dumps()将文件写成JSON
  • 使用json.laods()将文件作为JSON加载
  • 将数据加载与分析分离到单独的逻辑代码块中。e、 g:功能

对于复杂度为O(1)的查找,Pythondict(s)要比具有O(n)的迭代快得多,因此只要您最初加载数据文件,就可以获得一些性能优势。在

示例:

from json import dumps, loads


def load_data(filename):
    return json.loads(open(filename, "r").read())

def save_data(filename, data):
    with open(filename, "w") as f:
        f.write(dumps(data))

data = load_data("data.json")

foo = data["word"]  # O(1) lookup of "word"

我可能会这样存储你的数据:

^{pr2}$

然后你会:

stats = data.get(word, None)
if stats is not None:
    score, x, y = stats
    ...

NB:这些...不是实际代码和占位符,您应该在这些地方填充空格。在

相关问题 更多 >

    热门问题