我有一个单词列表,我需要找到字符串中存在的单词数。例如:text_string = 'I came, I saw, I conquered!'word_list=['I','saw','Britain']我需要一个打印的python脚本{‘i’:3,’saw’:1,’britain':0}
3 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
您可以使用re.findall查找 中的所有单词text_string,然后使用collections.Counter生成单词的 dict 及其计数,并使用 dict comprehension 根据 中的单词word_list及其在 dict 生成的 dict 中的相应计数生成字典Counter:
from collections import Counter
import re
c = Counter(re.findall(r'[a-z]+', text_string.lower()))
print({w: c.get(w, 0) for w in map(str.lower, word_list)})
这输出:
{'i': 3, 'saw': 1, 'britain': 0}

慕仙森
TA贡献1827条经验 获得超8个赞
使用 dict
前任:
text_string = 'I came, I saw, I conquered!'
word_list=['I','saw','Britain']
text_string = text_string.lower()
print(dict((i, text_string.count(i)) for i in map(str.lower, word_list)))
输出:
{'i': 3, 'britain': 0, 'saw': 1}
添加回答
举报
0/150
提交
取消