1 Star 0 Fork 0

王炳文 / 词频统计

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
word_freq.py 1.47 KB
一键复制 编辑 原始数据 按行查看 历史
王炳文 提交于 2019-03-28 16:57 . 第一次上传
# filename: word_freq.py
# 阅读注释,在所有pass处删除pass,添加代码
from string import punctuation
def process_file(dst): # 读文件到缓冲区
try: # 打开文件
file = open(dst,'r')
except IOError as s:
print (s)
return None
try: # 读文件到缓冲区
bvffer=file.read()
except:
print ("Read File Error!")
return None
file.close
return bvffer
def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
bvffer=bvffer.lower()
for x in '~!@#$%^&*()_+/*-+\][':
bvffer=bvffer.replace(x, " ")
words=bvffer.strip().split()
for word in words:
word_freq[word]=word_freq.get(word,0)+1
return word_freq
def output_result(word_freq):
if word_freq:
sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
for item in sorted_word_freq[:10]: # 输出 Top 10 的单词
print (item)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dst')
args = parser.parse_args()
dst = args.dst
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)
1
https://gitee.com/wbwwbw/word_frequency.git
git@gitee.com:wbwwbw/word_frequency.git
wbwwbw
word_frequency
词频统计
master

搜索帮助