python-3.x - 如何从棕色语料库中获取动词、名词、形容词?

标签 python-3.x nlp nltk corpus pos-tagger

我一直试图从棕色语料库中单独获取所有名词、动词等,所以我尝试使用代码

brown.all_synsets('n')

但显然这段代码仅适用于 wordnet。顺便说一句,我正在使用 python 3.4。


已编辑

@alvas 的回答有效。但是当我随机使用它时会出现错误。看看吧。

nn = {word for word, pos in brown.tagged_words() if pos.startswith('NN')}
print(nn)

输出为

{'such', 'rather', 'Quite', 'Such', 'quite'}

但是当我使用

random.choice(nn)

我明白了

Traceback (most recent call last):
  File "/home/aziz/Desktop/2222.py", line 5, in <module>
    print(random.choice(NN))
  File "/usr/lib/python3.4/random.py", line 256, in choice
    return seq[i]
TypeError: 'set' object does not support indexing

最佳答案

TL;DR

>>> from nltk.corpus import brown
>>> {word for word, pos in brown.tagged_words() if pos.startswith('NN')}

更长

迭代 .tagged_words() 函数,该函数将返回 ('word', 'POS') 元组列表:

>>> from nltk.corpus import brown
>>> brown.tagged_words()
[(u'The', u'AT'), (u'Fulton', u'NP-TL'), ...]

请阅读本章以了解 NLTK 语料库 API 的工作原理:http://www.nltk.org/book/ch02.html

然后,对其进行列表理解并保存一组用名词标签标记的单词(即唯一列表),例如NN、NNS、NNP 等

>>> {word for word, pos in brown.tagged_words() if pos.startswith('NN')}

请注意,输出可能不是您所期望的,因为用句法和句法名词标记的单词不一定是语义参数/实体


此外,我认为您提取的单词不正确。仔细检查列表:

>>> nouns = {word for word, pos in brown.tagged_words() if pos.startswith('NN')} 
>>> 'rather' in nouns
False
>>> 'such' in nouns
False
>>> 'Quite' in nouns
False
>>> 'quite' in nouns
False
>>> 'Such' in nouns
False

列表理解的输出:http://pastebin.com/bJaPdpUk


nn是一个集合时,为什么random.choice(nn)会失败?

random.choice() 的输入是一个序列(参见 https://docs.python.org/2/library/random.html#random.choice )。

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

而python中的python序列类型是

由于 set 不是序列,因此您将收到 IndexError

关于python-3.x - 如何从棕色语料库中获取动词、名词、形容词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477757/

相关文章:

python - NLTK树中叶子的绝对位置

c# - 用于命名实体识别器的C#工具

python - Porter Stemmer 可以返回词缀而不是词干吗?

python - nltk 模块中的类似方法在不同的机器上会产生不同的结果。为什么?

python - PyCharm 错误 - 加载项目 : Cannot load facet Python 时出错

r - 如何修复prettytable以正确显示汉字

nlp - 多任务学习

python - 保存 NLTK HMM 时出错

python-3.x - 使用自定义目标/损失函数的随机森林回归器(Python/Sklearn)

Python 3.6 : rename column header using DictWriter