python-词频统计-中英文

#CalHamletV1.py#英文统计程序
def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
 
hamletTxt = getText()
words  = hamletTxt.split()#split默认用空格分割字符串,返回列表,后是无空格的单词列表
counts = {}#创建字典
for word in words:           
    counts[word] = counts.get(word,0) + 1#遍历字典的键并对相应值+1,达到统计目的
items = list(counts.items())#items函数返回所有键值对元组,再用list返回列表类型,其中每个元素都是一个键值对
items.sort(key=lambda x:x[1], reverse=True) #按照键值对中的【1】就是第二个元素排序,逆序==从大到小(默认从小到大)
for i in range(10):
    word, count = items[i]#键值对赋值给word,count
    print ("{0:<10}{1:>5}".format(word, count)

#CalThreeKingdomsV1.py
import jieba
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(15):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

#CalThreeKingdomsV2.py
import jieba    #导入jieba第三方库(需要提前用在cmd中用pip install 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    #按键查找并对值累加计数,其中dict.get()方法,第二个参数是默认值,
for word in excludes:
    del counts[word]    #遍历exludes集合 删除对应字典中的键及值对
items = list(counts.items()) #Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组似乎不用再用list创建函数转换
items.sort(key=lambda x:x[1], reverse=True) #lambuda匿名函数,key参数,按照元组x中第二个元素,从大到小排序
for i in range(10):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

你可能感兴趣的:(python)