我刚刚开始使用NLTK,我不太明白如何从文本中获取单词列表。如果我使用nltk.word_tokenize()
,我会得到一个单词和标点符号的列表。相反,我只需要文字。我怎样才能摆脱标点符号?此外,word_tokenize
不能处理多个句子:在最后一个单词上添加圆点。
发布于 2013-03-22 02:19:49
看看nltk为here提供的其他标记化选项。例如,您可以定义一个标记器,该标记器将字母数字字符序列选作令牌,并删除其他所有字符:
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven miles to go, yet. Onward!')
输出:
['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']
发布于 2016-12-08 01:51:33
下面的代码将删除所有标点符号以及非字母字符。从他们的书里抄来的。
http://www.nltk.org/book/ch01.html
import nltk
s = "I can't do this now, because I'm so tired. Please give me some time. @ sd 4 232"
words = nltk.word_tokenize(s)
words=[word.lower() for word in words if word.isalpha()]
print(words)
输出
['i', 'ca', 'do', 'this', 'now', 'because', 'i', 'so', 'tired', 'please', 'give', 'me', 'some', 'time', 'sd']
发布于 2013-03-22 01:19:21
正如注释以sent_tokenize()开头所指出的,因为word_tokenize()只适用于单个句子。您可以使用filter()过滤掉标点符号。如果你有一个unicode字符串,确保它是一个unicode对象(而不是像‘utf-8’这样的编码的'str‘)。
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
https://stackoverflow.com/questions/15547409
复制相似问题