# 统计单词出现次数并把结果输出成字典
# 数据输入
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)
过滤,拆分,列表,字典
最新推荐文章于 2024-06-25 12:35:14 发布