【发布时间】: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 语句?
【问题讨论】:
-
Counter是dict的子类,因此如果word实际存在于vocabulary中,if word in vocabulary应该可以工作,如果您在word中生成正确的值,请检查您的逻辑 -
我尝试了
if word in wordFrequency,程序按预期运行。这些语句与most_common生成的计数器的工作方式是否不同?
标签: python collections counter