文章目录
- 1、统计文件中出现的所有中文字符及标点符号的数量
- 2、统计文本中出现引号的字符占文本总字符的比例
- 3、统计出现次数最多的8个词语
1、统计文件中出现的所有中文字符及标点符号的数量
- 题:统计文件中出现的所有中文字符及标点符号的数量,字符与数量用冒号隔开
如,“命:1024”
fi = open("a.txt", 'r', encoding='gbk')
fo = open("b.txt", 'w', encoding='gbk')
txt = fi.read()
d = {}
for c in txt:
d[c] = d.get(c, 0)+1
ls = []
for key in d:
ls.append("{}:{}".format(key, d[key]))
fo.write(','.join(ls))
fi.close()
fo.close()
2、统计文本中出现引号的字符占文本总字符的比例
- 题:统计文本中出现引号的字符占文本总字符的比例,如,“命:20%”,提示:比例=字符数/文本长度
fi = open("a.txt", 'r', encoding='gbk')
txt = fi.read()
con = 0
flag = False
for c in txt:
if c == '“':
flag = True
if c == '”':
flag = False
if flag:
con += 1
print("占总字符比例:{:.0%}。".format(con/len(txt)))
fi.close()
这里面的a.txt便是上文中的那个a.txt
3、统计出现次数最多的8个词语
- 题:统计文本文件中出现的中文词及其对应的次数,并输出出现次数最多的8个词语
import jieba
fi = open("a.txt", 'r', encoding='gbk')
txt = fi.read()
fi.close()
ls = jieba.lcut(txt)
dic = {}
for w in ls:
dic[w] = dic.get(w,0) + 1
rst = []
for i in range(8):
mx = 0
mxj = 0
for j in dic:
if dic[j] > mx:
mx = dic[j]
mxj = j
rst.append(mxj)
del dic[mxj]
print(",".join(rst))
for key in dic:
rst.append("{}:{}".format(key, dic[key]))
print(",".join(rst))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)