python文本统计

# -*- coding: utf-8 -*-
def getText():
    txt = open("TxtData19.txt","r",encoding='UTF-8').read()
    txt = txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
    return txt
 
TxtData19 = getText()
words  = TxtData19.split()
counts = {}
for word in words:           
    counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
#将文本词频出现的排名显示出来
for i in range(1000): 
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))
作者:ChenBD
发布了146 篇原创文章 · 获赞 213 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/s0302017/article/details/103763047