为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标琳琳 2021-06-21 18:09:26
我有一个单词列表,我需要找到字符串中存在的单词数。例如: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}


查看完整回答
反对 回复 2021-06-22
?
慕仙森

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}


查看完整回答
反对 回复 2021-06-22
  • 3 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号