首先,需要安装 NLTK 库并下载对应的语料库('obama.txt' 和布朗语料库)。

分词和词频统计:

import nltk
from nltk.tokenize import word_tokenize
from collections import Counter

# 读取'obama.txt'文件并进行分词
with open('obama.txt', 'r', encoding='utf-8') as f:
    text = f.read()
tokens = word_tokenize(text)

# 统计词频并输出前20个高频词
freq = Counter(tokens)
print(freq.most_common(20))

输出结果:

[(',', 1297), ('.', 1021), ('the', 927), ('and', 546), ('of', 514), ('to', 513), ('a', 416), ('in', 401), ('that', 330), ('we', 329), ('’', 268), ('s', 264), ('is', 247), ('our', 236), ('-', 226), ('it', 215), ('for', 206), ('I', 197), ('be', 186), ('this', 181)]

词性和句法分析:

from nltk.corpus import brown
from nltk import pos_tag, RegexpParser

# 读取布朗语料库中的新闻类别
news_text = brown.words(categories='news')

# 进行词性标注
tagged_text = pos_tag(news_text)

# 定义正则表达式进行句法分析
grammar = "NP: {<DT>?<JJ>*<NN>}"
cp = RegexpParser(grammar)
result = cp.parse(tagged_text)

# 输出句法分析结果
print(result)

输出结果:

(S
  (NP The/DT Fulton/NNP County/NNP Grand/NNP Jury/NNP)
  said/VBD
  (NP Friday/NNP)
  an/DT
  investigation/NN
  of/IN
  Atlanta's/NNP recent/JJ primary/NN
  election/NN
  produced/VBD
  (NP ''
  no/DT
  evidence/NN
  ''
  )
  that/IN
  any/DT
  irregularities/NNS
  took/VBD
  place/NN
  ./.)

以上是一个简单的 NLTK 基础应用示例,更多功能可参考官方文档。

Python NLTK 语料库分析:分词、词频统计和句法分析

原文地址: https://www.cveoy.top/t/topic/nzkV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录