加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
word_freq.py 1.66 KB
一键复制 编辑 原始数据 按行查看 历史
关显然 提交于 2019-04-08 14:37 . 更新 word_freq.py
def process_file(dst): # 读文件到缓冲区
try: # 打开文件
- pass
- except IOError, s:
- print s
+
+ file = open(dst,'r')
+
+ except IOError as s:
+ print (s)
return None
try: # 读文件到缓冲区
- pass
+ bvffer = f.read()
except:
- print "Read File Error!"
+ print ('Read File Error!')
return None
- pass
+ file.close()
return bvffer
@@ -24,17 +26,29 @@ def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq
- pass
-
+ bvffer = bvffer.lower()
+ for i in '“‘!;,.?”':
+ bvffer = bvffer.replace(i," ")
+ 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)
+
+def main():
+
+ dst = "Gone_with_the_wind.txt"
+ bvffer = process_file(dst)
+ word_freq = process_buffer(bvffer)
+ output_result(word_freq)
+
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
@@ -43,4 +57,4 @@ if __name__ == "__main__":
dst = args.dst
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
- output_result(word_freq)
\ No newline at end of file
+ output_result(word_freq)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化