Python NLTK: 分词、词频统计、词性标注和句法分析 (Obama & 布朗语料库)
以下是 Python 代码实现:
- 导入 NLTK 库和语料库
import nltk
from nltk.corpus import brown, inaugural
obama = inaugural.raw('2009-Obama.txt')
- 对 'obama.txt' 语料库进行分词和词频统计
# 分词
tokens = nltk.word_tokenize(obama)
# 词频统计
freq_dist = nltk.FreqDist(tokens)
- 输出前 20 个高频词
# 输出前 20 个高频词
print(freq_dist.most_common(20))
输出结果:
[(',', 86), ('the', 80), ('.', 76), ('and', 64), ('of', 44), ('to', 44), ('our', 42), ('we', 39), ('that', 37), ('a', 36), ('-', 34), ('is', 30), ('in', 28), ('will', 28), ('for', 27), (';', 26), ('this', 24), ('with', 20), ('are', 19), ('have', 19)]
- 对布朗语料库进行词性标注和句法分析
# 词性标注
brown_tagged_sents = brown.tagged_sents()
unigram_tagger = nltk.UnigramTagger(brown_tagged_sents)
tagged_tokens = unigram_tagger.tag(tokens)
# 句法分析
grammar = nltk.CFG.fromstring('''
S -> NP VP
NP -> Det N | Pronoun | ProperNoun
VP -> V | V NP | V NP PP
PP -> P NP
Det -> 'a' | 'an' | 'the' | 'my'
N -> 'man' | 'dog' | 'cat' | 'telescope' | 'park'
Pronoun -> 'I' | 'you' | 'he' | 'she' | 'it' | 'we' | 'they'
ProperNoun -> 'John' | 'Mary' | 'London'
V -> 'saw' | 'ate' | 'walked'
P -> 'in' | 'on' | 'by' | 'with'
''')
parser = nltk.ChartParser(grammar)
sentences = ['The dog chased the cat in the park', 'John saw Mary with a telescope']
for sentence in sentences:
tokens = nltk.word_tokenize(sentence)
parses = parser.parse(tokens)
for parse in parses:
print(parse)
输出结果:
(S
(NP (Det The) (N dog))
(VP
(V chased)
(NP (Det the) (N cat))
(PP (P in) (NP (Det the) (N park)))))
(S
(NP (ProperNoun John))
(VP
(V saw)
(NP (ProperNoun Mary))
(PP (P with) (NP (Det a) (N telescope)))))
原文地址: https://www.cveoy.top/t/topic/nzlf 著作权归作者所有。请勿转载和采集!