我一直试图从棕色语料库中单独获取所有名词、动词等,所以我尝试使用代码
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序列类型是
Python 2.x 中的 str、unicode、list、tuple、bytearray、buffer、xrange
(请参阅 https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange)。- Python 3.x 中的
列表、元组、范围
(请参阅 https://docs.python.org/3.6/library/stdtypes.html#sequence-types-list-tuple-range) - (二进制序列类型)Python 3.x 中的
字节、字节数组、内存 View
- (文本字符串序列)Python 3.x 中的
str
由于 set
不是序列,因此您将收到 IndexError
。
关于python-3.x - 如何从棕色语料库中获取动词、名词、形容词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477757/