文本文件“红楼梦. txt”中包含了《红楼梦》小说前20章内容,“ 停用词. txt”包含了需要排除的词语。实现以下功能。
1.对“红楼梦. txt”中文本进行分词,并对人物名称进行归-化处理,仅归一化以下内容:
凤姐、凤姐儿、凤丫头归-为凤姐
宝玉、二爷、宝二爷归-为宝玉
黛玉、颦儿、林妹妹、黛玉道归-为黛玉
宝钗、宝丫头归一为宝钗
贾母、老祖宗归-为贾母
袭人、袭人道归一为袭人
贾政、贾政道归一为贾政
贾链、琏二爷归一为贾琏
2.不统计“停用词.txt"文件中包含词语的词频(名字必须大于一个字)。
3.提取出场次数不少于40次的人物名称,将人物名称及其出场次教按照递减排序,保存到result.csv文件中,出场次数相同的.则按照人物名称的字符顺序排序。
输出示例
宝玉,597
凤姐,296
一个,179
如今,132
黛玉,113
一面,112
方法1:
import jieba
f = "红楼梦.txt"
sf = "停用词.txt"
f1=open(f,'r',encoding='utf-8')
txt=jieba.lcut(f1.read())
f2=open(sf,'r',encoding='utf-8')
lines=f2.readlines()
ty=[] #存放停用词
for line in lines:
ty.append(line[:-1]) #去掉行尾换行符
txt0=[] #存放剔除停用词后的红楼梦文本
for x in txt:
if x not in ty:
txt0.append(x)
d={}
for word in txt0:
if len(word)<=1:
continue
elif word == '凤姐儿' or word == '凤丫头':
rword = '凤姐'
elif word == '二爷' or word == '宝二爷':
rword = '宝玉'
elif word == '颦儿' or word == '林妹妹' or word == '黛玉道':
rword = '黛玉'
elif word == '宝丫头':
rword = '宝钗'
elif word == '老祖宗':
rword = '贾母'
elif word == '袭人道':
rword = '袭人'
elif word == '贾政道':
rword = '贾政'
elif word == '琏二爷':
rword = '贾琏'
else:
rword=word
d[rword]=d.get(rword,0)+1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True)
fo=open(r'result.csv', 'a', encoding='utf-8')
for i in ls:
if i[1]>=40:
print("{},{}".format(i[0],i[1]))
fo.write("{},{}\n".format(i[0],i[1]))
f1.close()
f2.close()
fo.close()
方法2:
import jieba
f = "红楼梦.txt"
sf = "停用词.txt"
txt = jieba.lcut(open(f, 'r', encoding='utf-8').read()) # open函数读取红楼梦文本并分词 ,正式考试可以不用指定编码,用系统默认。 f.read()读入全部内容。jieba.lcut()返回一个列表类型的分词结果。
stop_words = []
with open(sf, 'r', encoding='utf-8') as f: # 读取停用词文本并分割文本后添加到stop_words列表中。with语句打开文件,好处是读取文件后自动关闭,不需要手动关闭。
for i in f.read().splitlines(): #str.splitlines([keepends]):返回一个列表,分割符为('\r','\r\n','\n')即按行分割。默认参数keepends为False,意思是不保留每行结尾的'\n',反之保留。
stop_words.append(i)
# 剔除停用词
txt0 = [x for x in txt if x not in stop_words]
# 统计词频
counts = {}
for word in txt0:
if len(word) == 1: # 跳过标点符号和字
continue
elif word == '凤姐儿' or word == '凤丫头':
rword = '凤姐'
elif word == '二爷' or word == '宝二爷':
rword = '宝玉'
elif word == '颦儿' or word == '林妹妹' or word == '黛玉道':
rword = '黛玉'
elif word == '宝丫头':
rword = '宝钗'
elif word == '老祖宗':
rword = '贾母'
elif word == '袭人道':
rword = '袭人'
elif word == '贾政道':
rword = '贾政'
elif word == '琏二爷':
rword = '贾琏'
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
# 固定语句将字典的值进行排序
li = list(counts.items())
li.sort(key=lambda x: x[1], reverse=True)
# 列出词频超过40的结果
with open('result.csv', 'a', encoding='gbk') as f:
for i in li:
key, value = i
if value < 40:
break
f.write(key + ',' + str(value) + '\n') #value为int
print(key + ',' + str(value))