- 代码
- 运行结果
import string
s = 'not talk,not helo show me your code hello helo'
for i in s:
'''变例s中的字符,如果属于标点符号则替换成空格'''
if i in string.punctuation:
s = s.replace(i, ' ')
# print(s)
lst = s.split()
# s被空格分割形成的列表传给lst
d = {} # 创建一个空字典来存储各单词与其出现的次数
for i in lst:
'''d.keys()返回一个字典的关键字列表,
如果单词i在属于字典关键字则其对应的value+1,
否则就是第一次出现,添加一个新关键字,其值为1'''
if i in d.keys():
d[i] += 1
else:
d[i] = 1
print(d)
运行结果



