编程输入一段英文,统计英文中单词出现的次数,并输出结果。
https://ask.csdn.net/questions/7451077,https://ask.csdn.net/questions/7451170,你的好几位同学都有过提问了。。。
如有帮助,还望采纳
# 统计单词出现次数并把结果输出成字典
# 数据输入
str = "Hello world, There are some test words. Hello world, There are some test words. Haha!"
# 过滤规则:过滤掉所有非字母的字符
import re
str = re.sub(r"[^a-zA-Z]+", " ",str)
print("过滤后的字符串:",str)
#拆分成列表
str = str.split(" ")
# 去除多余的空项
str.remove("")
print("拆分成列表:",str)
# 生成字典的key列表
dict_keys = []
for i in str:
if i not in dict_keys:
dict_keys.append(i)
print("key列表:",dict_keys)
# 输出字典
# 定义空字典
words_dict = {}
# 往字典写入key值
words_dict.fromkeys(dict_keys)
# 遍历key列表,利用count函数统计单词出现次数
for j in dict_keys:
words_dict[j] = str.count(j)
print("字典:",words_dict)
如果对你有帮助,可以点击我这个回答右上方的【采纳】按钮,给我个采纳吗,谢谢
import re
s = 'The secret of success (The key to success) is not so much money as a strong will. \
A great man is one who has a strong will and an indomitable spirit. In other words, \
if a man does not have a strong will to win (get) the final victory, he will never \
succeed in his life. He is no more than a failure.'
a = '[,.()!?]'
sr = re.sub(a, '', s).split() # 去除标点符号,根据空格分词
sr = [i.lower() for i in sr] # 将所有单词转化为小写
# print(sr)
words = set(sr) # 去重
for i in words: # 统计每个词出现的次数
print('{0}出现的次数为:{1}'.format(i, sr.count(i))) # 输出词和词频
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps: 问答会员年卡【8折】购 ,限时加赠IT实体书,即可 享受50次 有问必答服务,了解详情>>>https://t.csdnimg.cn/RW5m