来自另一个列表的字符串中的单词数

我有一个单词列表,我需要找到字符串中存在的单词数。


例如:


text_string = 'I came, I saw, I conquered!'

word_list=['I','saw','Britain']

我需要一个打印的python脚本


{‘i’:3,’saw’:1,’britain':0}


慕标琳琳
浏览 148回答 3
3回答

凤凰求蛊

您可以使用re.findall查找 中的所有单词text_string,然后使用collections.Counter生成单词的 dict 及其计数,并使用 dict comprehension 根据 中的单词word_list及其在 dict 生成的 dict 中的相应计数生成字典Counter:from collections import Counterimport rec = 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}

慕仙森

使用 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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python