从句子列表创建标记是返回字符而不是单词

时间:2016-07-07 07:07:48

标签: python text nlp nltk tokenize

from nltk.tokenize import sent_tokenize

text = open(path).read().lower().decode("utf8")
sent_tokenize_list = sent_tokenize(text)

tokens = [w for w in itertools.chain(*[sent for sent in sent_tokenize_list])]

最后一行“令牌”返回字符而不是单词。

为什么会这样,如何让它返回单词呢?特别是考虑根据句子列表来做。

3 个答案:

答案 0 :(得分:2)

因为sent_tokenize返回一个字符串句子列表,并且itertools.chain个链迭代到一个迭代,每次返回一个项目,直到它们都用完为止。实际上,您已将句子重新组合为单个字符串,并在列表解析中对其进行迭代。

要从句子列表中创建单个单词列表,您可以拆分并展平:

tokens = [word for sent in sent_tokenize_list for word in sent.split()]

这不会处理标点符号,但您的原始尝试也不会。您的原件也适用于拆分:

tokens = [w for w in itertools.chain(*(sent.split()
                                       for sent in sent_tokenize_list))]

请注意,您可以使用生成器表达式而不是列表解析作为解包的参数。更好的是,使用chain.from_iterable

tokens = [w for w in itertools.chain.from_iterable(
    sent.split() for sent in sent_tokenize_list)]

对于标点符号处理,请使用nltk.tokenize.word_tokenize代替str.split。它会将单词和标点符号作为单独的项返回,并将I's分为I's(这当然是一件好事,因为它们实际上是单独的单词,只是收缩)。

答案 1 :(得分:1)

您可以使用word_tokenize代替sent_tokenize吗?

from nltk.tokenize import word_tokenize

text = open(path).read().lower().decode("utf8")
tokens = word_tokenize(text)

http://www.nltk.org/api/nltk.tokenize.html#nltk.tokenize.word_tokenize

答案 2 :(得分:1)

首先,如果文件位于“utf8”中。并且您正在使用Python2,如果您使用io.open()中的encoding='utf8'参数,它会更好:

import io

from nltk import word_tokenize, sent_tokenize

with io.open('file.txt', 'r', encoding='utf8') as fin:
    document = []
    for line in fin:
        tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]

如果是Python3,只需执行:

from nltk import word_tokenize 

with open('file.txt', 'r') as fin:
    document = []
    for line in fin:
        tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]

请查看http://nedbatchelder.com/text/unipain.html

至于标记化,如果我们假设每行包含某种可能由一个或多个句子组成的段落,我们首先要初始化一个列表来存储整个文档:

document = []

然后我们遍历这些行并将该行分成句子:

for line in fin:
    sentences = sent_tokenize(line)

然后我们将句子分成标记:

token = [word_tokenize(sent) for sent in sent_tokenize(line)]

由于我们想要更新我们的文档列表来存储标记化的句子,我们使用:

document = []
for line in fin:
    tokens += [word_tokenize(sent) for sent in sent_tokenize(line)]

不推荐!!! (但仍然可以在一行中):

alvas@ubi:~$ cat file.txt
this is a paragph. with many sentences.
yes, hahaah.. wahahha... 
alvas@ubi:~$ python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
>>> from itertools import chain
>>> from nltk import sent_tokenize, word_tokenize
>>> list(chain(*[[word_tokenize(sent) for sent in sent_tokenize(line)] for line in io.open('file.txt', 'r', encoding='utf8')]))
[[u'this', u'is', u'a', u'paragph', u'.'], [u'with', u'many', u'sentences', u'.'], [u'yes', u',', u'hahaah..', u'wahahha', u'...']]