python123模拟题B综合应用题


1.AC代码展示


给的参考答案没有对标点符号进行剔除,这里用正则表达式删除标点

import re #引入正则库
import jieba
fi=open("天龙八部-网络版.txt","r",encoding="utf-8")
fo1=open("天龙八部-汉字统计.txt","w",encoding="utf-8")
fo2=open("天龙八部-词语统计.txt","w",encoding="utf-8")
txt=fi.read()
newtxt1= re.sub("[\s]", "",txt)
newtxt2= re.sub("[\:;\-\s+\.\!\/_,$%^*(+\"\')\[\]\{\}\`]+|[\·\:;《》‘’“”+——!,。??、~@#¥%……&*()]+", "",txt)
d1={}
d2={}
for c in newtxt1:
    d1[c]=d1.get(c,0)+1
ls1=[]
for key in d1:
    ls1.append("{}:{}".format(key,d1[key]))
fo1.write(",".join(ls1))
words=jieba.lcut(newtxt2)for w in words:
    d2[w]=d2.get(w,0)+1
ls2=[]
for key in d2:
    ls2.append("{}:{}".format(key,d2[key]))
fo2.write(",".join(ls2))
fi.close()
fo1.close()
fo2.close()

2.出于兴趣

1.按词频排序
2.输出词云
import re #引入正则库
import jieba
import wordcloud
fi=open("天龙八部-网络版.txt","r",encoding="utf-8")
fo1=open("天龙八部-汉字统计.txt","w",encoding="utf-8")
fo2=open("天龙八部-词语统计.txt","w",encoding="utf-8")
txt=fi.read()
newtxt1= re.sub("[\s]", "",txt)
newtxt2= re.sub("[\:;\-\s+\.\!\/_,$%^*(+\"\')\[\]\{\}\`]+|[\·\:\;\‘\’《》“”+——!,。??、~@#¥%……&*()]+", "",txt)
d1={}
d2={}
for c in newtxt1:
    d1[c]=d1.get(c,0)+1

#自定义任务统计词频后排序
d1_sort=sorted(d1.items(),key=lambda x:x[1],reverse=True)
#key=lambda x:x[1]对值排序
#key=lambda x:x[0]对键排序
#sorted返回元组列表list of tupple

ls1=[]
for dui in d1_sort:
    ls1.append("{}:{}".format(dui[0],dui[1]))


fo1.write(",".join(ls1))
words=jieba.lcut(newtxt2)
for w in words:
    d2[w]=d2.get(w,0)+1
    
#自定义任务统计词频后排序
d2_sort=sorted(d2.items(),key=lambda x:x[1],reverse=True)
ls2=[]
for dui in d2_sort:
    ls2.append("{}:{}".format(dui[0],dui[1]))
fo2.write(",".join(ls2))

#自定义任务生成词云
ls3=[]
for dui in d2_sort:
    ls3.append(dui[0])
#准备生成词云的长文本
words=" ".join(ls3)
w=wordcloud.WordCloud(\
    font_path="C:\\Windows\\Fonts\\simkai.ttf",\
    width=1000,height=700,background_color="white",\
    max_words=15)
w.generate(words)
w.to_file("天龙八部.png")

fi.close()
fo1.close()
fo2.close()

3.展示


图1. 生成的词云文件
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值