NLTK set方法打印字符,而不是单词

时间:2013-12-20 21:53:02

标签: python nlp nltk

我是NLTK(和python ...)的新手,我的一个基本方法遇到两个问题:当我打电话时

sorted(set(<one of nltk's preloaded corpora>))

它打印出文本中所有单词的列表,但每个单词前面都有'u',如下所示:[u'yourselves',u'youth']。我以为我已经破坏了标记器,但我尝试重新克隆存储库并重新安装。

第二个可能相关的问题是,当我在自己传递的字符串上使用这些方法定义尝试时,我得到的是单个字符,而不是单词。我是否需要解析在使用set()之前传入的文本?

1 个答案:

答案 0 :(得分:0)

u'foo bar' 只是unicode中的一个字符串。 strunicode都被视为basestring(请参阅http://docs.python.org/2/howto/unicode.htmlhttp://docs.python.org/2/library/functions.html#basestring

>>> x = u'foobar'
>>> isinstance(x, str)
False
>>> isinstance(x,unicode)
True
>>> isinstance(x,basestring)
True
>>> print x
foobar

当您尝试从NLTK的语料库读取器访问语料库时,默认数据结构是一个句子列表,其中每个句子都是一个标记列表,每个标记都是一个基本字符串。

>>> from nltk.corpus import brown
>>> print brown.sents()
[['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'], ['The', 'jury', 'further', 'said', 'in', 'term-end', 'presentments', 'that', 'the', 'City', 'Executive', 'Committee', ',', 'which', 'had', 'over-all', 'charge', 'of', 'the', 'election', ',', '``', 'deserves', 'the', 'praise', 'and', 'thanks', 'of', 'the', 'City', 'of', 'Atlanta', "''", 'for', 'the', 'manner', 'in', 'which', 'the', 'election', 'was', 'conducted', '.'], ...]

如果你想要一个纯文本版本的语料库,你可以简单地做:

>>> for i in brown.sents():
...     print " ".join(i)
...     break
... 
The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place .

NLTK中有许多内部魔法使得语料库可以从NLTK的模块中工作,但是知道这些“预加载”语料库(或更准确地说是“预编码”语料库读取器)中的内容的最简单方法是使用:

>>> dir(brown)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add', '_c2f', '_delimiter', '_encoding', '_f2c', '_file', '_fileids', '_get_root', '_init', '_map', '_para_block_reader', '_pattern', '_resolve', '_root', '_sent_tokenizer', '_sep', '_tag_mapping_function', '_word_tokenizer', 'abspath', 'abspaths', 'categories', 'encoding', 'fileids', 'open', 'paras', 'raw', 'readme', 'root', 'sents', 'tagged_paras', 'tagged_sents', 'tagged_words', 'words']