【问题标题】:If statement to check if an element is found in a counter (Python)if语句检查是否在计数器中找到元素(Python)
【发布时间】:2020-06-13 16:36:32
【问题描述】:

我正在编写一个程序,其中有一个名为 vocabulary 的计数器 (collections.counter),它是名为 wordFrequency 的计数器中最常用的 10,000 个计数器,该计数器是通过计算从文本文件中读取的单词实例得出的。我一直在尝试制作一个 if 语句来检查是否在该计数器中找到了一个元素。我所拥有的是:

vocabulary = wordFrequency.most_common(10000)

[...]

for line in trainReader2:
    if len(line) == 10 and line[5] != "_":
        if wordPosition < matrixWidth:
            word = line[1]
            if word in vocabulary:
                sentenceRow[wordPosition] = word
            else:
                sentenceRow[wordPosition] = "[unknown]"
            wordPosition += 1
    elif wordPosition != 0:
        trainingMatrix.append(sentenceRow)
        print("sentence row:", sentenceRow)
        wordPosition = 0
        sentenceRow = ["[padding]"] * matrixWidth

我认为if word in vocabulary: 肯定会起作用,但似乎永远不会满足条件,并且句子行总是完全由[unknown][padding] 组成。在这种情况下我应该使用什么 if 语句?

【问题讨论】:

  • Counterdict 的子类,因此如果word 实际存在于vocabulary 中,if word in vocabulary 应该可以工作,如果您在word 中生成正确的值,请检查您的逻辑
  • 我尝试了if word in wordFrequency,程序按预期运行。这些语句与most_common 生成的计数器的工作方式是否不同?

标签: python collections counter


【解决方案1】:

问题在于wordFrequency.most_common(10000) 返回的是元组列表,而不是字典。您需要将其设为字典或集合才能在其中查找单词。

vocabulary  = dict(wordFrequency.most_common(10000))

or 

vocabulary  = set(w for w,_ in wordFrequency.most_common(10000))

您还可以使用 most_common 中的最后一个值作为阈值,并将单词的频率值与其进行比较,而不是创建第二个单词列表(假设最后一个最常见的单词可能与其他单词具有相同的频率不包括在列表中)

minFreq =  wordFrequency.most_common(10000)[-1][1]

...  

if wordFrequency.get(word,0) >= minFreq: 

【讨论】:

    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多