# 读入文件‘monday.txt’.统计文件中每个单词的数量并且进行输出。
# txt的文本文件为
# Monday.txt的文本内容为
# The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a certain
# city of china. Based upon the data,we can see that the statistics of the gyms increased considerably from 1200 billion
# to 1800.
统计单词写入文件的方法:
s = 'The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a ' \
'certain city of china.Based upon the data,we can see that the statistics of the gyms increased considerably ' \
'from 1200 billion to 1800'
# 写将字符串写入
f = open('Monday.txt','w')
f.write(s)
f.close
# 导入模块
import collections
import re
def fun():
with open('Monday.txt', 'r') as fp:
content = re.split('[,. ]', fp.read())
print(content)
b = collections.Counter(content)
print(b)
with open('word2.txt', 'w') as result_file:
for key, value in b.items():
result_file.write(key + ':' + str(value) + '\n')
fun()
统计单词排序的方法二:
s = 'The pie chart above illustrates apparently the data of people doing exercise and the number of the gyms in a ' \
'certain city of china.Based upon the data,we can see that the statistics of the gyms increased considerably ' \
'from 1200 billion to 1800'
# 字符串替换
list1 = s.replace(',',' ')
list2 = list1.replace('.',' ')
print(list2)
# 字符串截取
list3 = list2.split(' ')
print(list3)
# 创建空字典
d = {}
# 遍历列表
for i in list3:
ss = d.get(i)
if ss == None:
d[i] = 1
else:
d[i] += 1
print(d)
# 将字典的值变为列表进行排序
d1 = sorted(d.items(),key=lambda x:x[1],reverse=True)
print(d1)