说明:读取一个TXT文件,然后统计其中所有的单词个数,并按照从多到少排序(python解释器版本:3.8)实例读取文件我已上传
代码:
# 练习三:统计tet单词频次:
import re
f = open('baofali.txt', encoding='gbk', errors="ignore")
txt = f.read() # 读取文件并存放资源
# txt = f.read(100) 从头开始读取的字符数
# tetalines=f.readlines() 读取操作,读取一行为一个元素
f.close()
txt = txt.lower() # 将字母全部转为小写
txt = re.sub('[鈥攈,.!?:攁"*\';,-,]', '', txt) # 字符替换,去除小说中的标点符号
word = txt.split() # 单词分割,以空格分隔
# 进行词频统计,由高到低排序
word_sq = {
}
for i in word:
if i not in word_sq.keys():
word_sq[i] = 1
else:
word_sq[i] += 1
# 无法对字典本身做排序操作
res = sorted(word_sq.items(), key=lambda x: x[1], reverse=True) # 升序排序
print(res)
输出(太长了):