Python 您所在的位置:网站首页 byproduct是什么意思中文 Python

Python

2023-08-26 11:51| 来源: 网络整理| 查看: 265

首先这里打开文件的时候要注意文件的编码问题!!! 英文的词频统计:

这里需要把《哈莫雷特》中出现的次数最多的单词(前十)打印出来

在英文中,不同的单词都是有明显的分隔的,有的是以空格分隔,有的是以逗号分隔......

这里我们需要把不同的单词分隔出来,所以我们要把所有可以用来分隔单词的符号都转换成空格,这样我们在分隔不同的单词的时候就只需要按空格分隔就可以了。

另外,单词有的是大写,有的是小写,所以我们这里需要把所有的单词的大小写统一一下。

#CalHamletV1.py def getText(): txt = open("hamlet.TXT", "r", encoding='UTF-8').read()#打开文件 txt = txt.lower()#全部转成小写 for ch in '!"#$%&()*+,-./:;?@[\\]^_‘{|}~': txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格 return txt hamletTxt = getText() words = hamletTxt.split() counts = {} for word in words: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True)#排序 for i in range(10): word, count = items[i] print ("{0:5}".format(word, count))

 

中文的词频统计:

这里需要把《三国演义》中出现的次数最多的人名(前十)打印出来

这里中文的分词和英文的是不一样的,英文有很明显 的符号进行区分,可是中文没有,所以这里就需要用到 Python中的第三方库  jieba库  来对中文文本进行分词

首先需要安装 jieba库

pip install jieba

然后 就可以直接使用jieba库 了

#CalThreeKingdomsV1.py import jieba txt = open("三国演义.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) == 1: continue else: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(10): word, count = items[i] print ("{0:5}".format(word, count))

这里可以看到,这里只做了词频统计。在出现次数前十的词语中有一些不是人名的,还有一些事重复的,所以在这里 就需要在词频统计的基础上面向问题,改造我们的程序。

#CalThreeKingdomsV2.py import jieba excludes = {"将军","却说","荆州","二人","不可","不能","如此"} txt = open("三国演义.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt) counts = {} for word in words: if len(word) == 1: continue elif word == "诸葛亮" or word == "孔明曰": rword = "孔明" elif word == "关公" or word == "云长": rword = "关羽" elif word == "玄德" or word == "玄德曰": rword = "刘备" elif word == "孟德" or word == "丞相": rword = "曹操" else: rword = word counts[rword] = counts.get(rword,0) + 1 for word in excludes: del counts[word] items = list(counts.items()) items.sort(key=lambda x:x[1], reverse=True) for i in range(10): word, count = items[i] print ("{0:5}".format(word, count))

这里还不是完整的,还需要不断的运行程序,来使结果满足我们的要求 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有