IR作业一 词频查询
1. 代码及注释如下:
def world_frequency(file):
"""读取文件,统计词频,生成index文件"""
# 创建字典
dic = dict()
# 读取文件,生成词典
read_file(file, dic)
# 读取字典,生成index文件
write_file(dic)
# 查询词的频次
word = input('请输入需要查询的单词:')
print('频次:'+str(dic.get(word, 0)))
def read_file(file, dic):
# 读取文件
with open(file, 'r') as fp:
# 生成词频字典
while True:
line = fp.readline()
# 结束条件
if line == '':
break
# 依据空格划分,生成列表
word_list = line.split(' ')
# 转换成小写读入,且只取单词
for i in word_list:
if i.upper() != i:
dic[i.lower()] = dic.get(i.lower(), 0) + 1
def write_file(dic):
# 读取字典,生成index文件
with open('dict.index', 'w') as fp1:
for i in dic:
fp1.write(i + '\t' + str(dic[i]) + '\n')
说明:
主函数 world_frequency:满足生成词典文件(dict.index),查询词频的功能
其他函数 read_file,write_file:分别执行读取,写入功能
2. 测试方法
在提示字符“请输入需要查询的单词:”后输入需要查询的单词,请注意小写。
评论0
最新资源