Python NLTK没有正确去除标点符号
我定义了以下代码:
exclude = set(string.punctuation)
lmtzr = nltk.stem.wordnet.WordNetLemmatizer()
wordList= ['"the']
answer = [lmtzr.lemmatize(word.lower()) for word in list(set(wordList)-exclude)]
print answer
我之前打印了 exclude,里面包含了引号 "。我本来期待输出是 [the]。可是,当我打印 answer 的时候,它显示的是 ['"the']。我不太明白为什么标点符号没有被正确去掉。难道我需要逐个检查每个字符吗?
1 个回答
1
当你从 wordList
创建一个集合时,它只会把字符串 '"the'
存储为唯一的元素。
>>> set(wordList)
set(['"the'])
所以使用集合的差集操作会返回同样的集合。
>>> set(wordList) - set(string.punctuation)
set(['"the'])
如果你只是想去掉标点符号,可能需要用类似这样的方式:
>>> [word.translate(None, string.punctuation) for word in wordList]
['the']
这里我使用了字符串的 translate
方法,只传入了一个第二个参数,指定要去掉哪些字符。
然后你可以在新的列表上进行词形还原。