这里我必须找到列表c中的单词,这些单词是否存在于语料库行中。
我希望答案是[1,3,2,4,1,4,1,4,4]
意思是单词";以及";出现在行3中,因此回答"是";1〃;
单词";文件";存在于行1、行2和行4中;3〃;等等
请更正我的程序,如果你有任何最简单的程序,也可以提出建议。谢谢
corpus= [
'this is the first document', #row1
'this document is the second document', #row2
'and this is the third one', #row3
'is this the first document', #row4
]
c=['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
a=[]
count=0
for words in c:
a.append(count)
count=0
for row in corpus:
if words in row:
count=count+1
print(a)
所有问题都是您在错误的位置使用了append()
。
您必须在for
-循环之后使用它。
for words in c:
count=0
for row in corpus:
if words in row:
count=count+1
a.append(count)
这似乎是有效的。
from collections import Counter
words = []
for corp in corpus:
words.extend(corp.split())
word_counts = Counter(words)
word_counts_list = []
for word in c:
if word not in word_counts:
word_counts_list.append(0)
else:
word_counts_list.append(word_counts[word])
不是你期望的结果,而是你期望的不正确的结果。
word_counts_list
Out[136]: [1, 4, 2, 4, 1, 1, 4, 1, 4]