我有以下列表:t = ['one', 'two', 'three']
我想读取一个文件并为列表中存在的每个单词添加一个点。例如。如果 "one"
和 "two"
存在于 "CV.txt
"中,points = 2。如果它们都存在,则 points = 3.
import nltk
from nltk import word_tokenize
t = ['one', 'two', 'three']
CV = open("cv.txt","r").read().lower()
points = 0
for words in t:
if words in CV:
#print(words)
words = nltk.word_tokenize(words)
print(words)
li = len(words)
print(li)
points = li
print(points)
假设 'CV.txt'
包含单词“one
”和“two
”,并且按单词拆分(标记化) ,应将 2 个点添加到变量“points
”
但是,此代码返回:
['one']
1
1
['two']
1
1
正如您所看到的,长度只有 1,但它应该是 2。我确信有一种更有效的方法可以使用迭代循环或其他方法而不是 len。 如有任何帮助,我们将不胜感激。
最佳答案
我认为您不需要在循环内进行标记化,因此可能更简单的方法如下:
- 首先对txt文件中的词进行分词
- 检查每个常用词
在
t
最后的点是 common_words
中的单词数。
import nltk
from nltk import word_tokenize
t = ['one', 'two', 'three']
CV = open("untitled.txt","r").read().lower()
points = 0
words = nltk.word_tokenize(CV)
common_words = [word for word in words if word in t]
points = len(common_words)
注意:如果你想避免重复,那么你需要一组常用词,如下面的代码:
common_words = set(如果单词在 t 中,则单词中的单词)
关于python - 比较列表和文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49260329/