最近在MOOC跟着北京理工大学的嵩天老师学习Python(https://www.icourse163.org/learn/BIT-268001?tid=1003243006#/learn/announce),受益匪浅,老师所讲的通俗易懂,推荐给大家。
在此记点笔记和注释,备忘。
今天所记得是文本词频统计-Hamlet文本词频统计。
英文文本
Hamlet词频统计文件链接:https://python123.io/resources/pye/hamlet.txt
直接上源代码
#CalHamletV1.py
def getText():
txt = open("E:\hamlet.txt", "r").read() #读取Hamlet文本文件,并返回给txt
txt = txt.lower() #将文件中的单词全部变为小写
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格
return txt
hamletTxt = getText()
words = hamletTxt.split() #按照空格,将文本分割
counts = {}
for word in words: #统计单词出现的次数,并存储到counts字典中
counts[word] = counts.get(word,0) + 1 #先给字典赋值,如果字典中没有word这个键,则返回0;见下面函数讲解
items = list(counts.items()) #将字典转换为列表,以便操作
items.sort(key=lambda x:x[1], reverse=True) # 见下面函数讲解
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
所用函数讲解:
①dict.get(key, default=None):函数返回指定键的值,如果值不在字典中返回默认值
②list.sort(cmp=None, key=None, reverse=False):
- cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
- key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)
中文文本
三国演义文本:https://python123.io/resources/pye/threekingdoms.txt
#CalThreeKingdomsV2.py
import jieba
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "诸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "关公" or word == "云长":
rword = "关羽"
elif word == "玄德" or word == "玄德曰":
rword = "刘备"
elif word == "孟德" or word == "丞相":
rword = "曹操"
else:
rword = word
counts[rword] = counts.get(rword,0) + 1
for word in excludes:
del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word, count = items[i]
print ("{0:<10}{1:>5}".format(word, count))
函数讲解:
jieba.lcut(s):精确分词模式,返回一个列表类型的分词结果。没有冗余。