Python自然语言分析(第四期):第3课书面作业

#  -*- coding: UTF-8 -*-
import nltk

#使用语料库模块处理 austen-persuasion.txt。这本书中有多少词标识符?多少词类型?
emma = nltk.corpus.gutenberg.words('austen-emma.txt')
len(emma)       #求取文本中的词标识符
len(set(emma))  #求取文本中的词类型

#在名字语料库上定义一个条件频率分布,显示哪个首字母在男性名字中比在女性名字中更常用
from nltk import ConditionalFreqDist
from nltk.corpus import names
import matplotlib
cfd = ConditionalFreqDist(
                          (fileid,w.lower()[0])
               for fileid in names.fileids()
               for w in names.words(fileid)
               )
cfd.plot()
#挑选两个文本,研究它们之间在词汇、词汇丰富性、文体等方面的差异。你能找出几
#个在这两个文本中词意相当不同的词吗?例如:在《白鲸记》与《理智与情感》中的 monstrous。
from nltk.book import *
print(len(text1))           # text1为白鲸记,是text格式,不必写作len(text1.words())
print(len(set(text1)))      # 白鲸记中的词汇量
print(len(set(text2)))      # 理智与情感中的词汇量

#按照新闻文体统计其中can、could、may、might、must、will出现的频数
from nltk.corpus import brown
next_text = brown.words(categories = 'news')
fdist = nltk.FreqDist([w.lower() for w in next_text])
modals = ['can', 'could', 'may', 'might', 'must', 'will']
for m in modals:
    print(m+':', fdist[m])

#查看白鲸记和情感与理智中的monstrous
text1.concordance('monstrous')
text2.concordance('monstrous')
text1.similar('monstrous')
text2.similar('monstrous')

#编写一段程序,找出所有在布朗语料库中出现至少3次的词
from nltk.corpus import brown
text = [w.lower() for w in brown.words() if w.isalpha()]
fdist = nltk.FreqDist(text)
freqList = list(fdist.items())
output = []
for m in freqList:
    if m[1] >= 3:
        output.append(m[0])
print(output)

#编写一个函数,找出文本中最常出现的50个词,停用词除外
def max_frequent_words(words):
    filtered_words = [w.lower() for w in words if w.lower() not in stopwords.words(fileids=u'english')]
    fdist = FreqDist(filtered_words)
    sorted_words = sorted(fdist.keys(),key=lambda x:fdist[x],reverse=True)
    return sorted_words[:50:]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值