【问题标题】:word analysis and scoring from a file python来自文件python的单词分析和评分
【发布时间】: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


【解决方案1】:

以下是我的建议:

  • 使用json.dumps() 将您的文件写成 JSON
  • 使用json.laods() 以 JSON 格式加载文件
  • 将数据加载与分析分离到单独的逻辑代码块中。例如:函数

Python dict(s) 对于复杂度为 O(1) 的查找比具有 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"

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

data = {
    "fabulous": [7.526, 2301, 2],
    ...
}

你会这样做:

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

注意:...不是真正的代码和占位符,您应该在其中填写空白。

【讨论】:

  • 能否请您给我看一个您的提示示例,因为我以前从未使用过 json。
  • dict 比迭代更好,你的意思是,将文件放入字典并进行查找而不是使用 for 循环?
  • 因为文件有 4 列,#fabulous 7.526 2301 2 那么如何检索第一列和第二列?
【解决方案2】:

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

这样的工作是否可行:

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

【讨论】:

  • 这段代码的输出是什么?它和我的有什么不同?
  • 单句的目标输出是多少?总结各种单词分数的字典,还是句子中每个单词的字典?这里的主要建议是将您的单词文件存储为一个大字典,以便在检查句子中的每个单词时获得 word_lookup.has_key() 的好处。
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 2021-01-27
  • 2012-03-21
  • 1970-01-01
  • 2021-10-10
  • 2012-05-30
  • 1970-01-01
  • 2011-01-22
相关资源
最近更新 更多