【发布时间】:2016-03-23 14:25:36
【问题描述】:
我正在尝试使用 NLTK 对正文中的单词进行字数统计。我正在阅读文本文件并尝试转换为小写、删除标点符号和标记化。然后删除停用词,然后计算最常见的词。但是,我收到以下错误:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
这是我的代码:
import nltk
import string
from nltk.corpus import stopwords
from collections import Counter
def get_tokens():
with open('/Users/user/Code/abstract/data/Training(3500)/3500_Response_Tweets. txt', 'r') as r_tweets:
text = r_tweets.read()
lowers = text.lower()
#remove the punctuation using the character deletion step of translate
no_punctuation = lowers.translate(None, string.punctuation)
tokens = nltk.word_tokenize(no_punctuation)
return tokens
tokens = get_tokens()
filtered = [w for w in tokens if not w in stopwords.words('english')]
count = Counter(filtered)
print count.most_common(100)
除了警告,我的输出看起来像:
[('so', 268), ('\xe2\x80\x8e\xe2\x80\x8fi', 231), ('like', 192), ('know', 157), ('dont', 137), ('get', 125), ('im', 122), ('would', 118), ('\xe2\x80\x8e\xe2\x80\x8fbut', 118), ('\xe2\x80\x8e\xe2\x80\x8foh', 114), ('right', 113), ('good', 105), ('\xe2\x80\x8e\xe2\x80\x8fyeah', 95), ('sure', 94), ('one', 92),
使用 codecs.open 时的回溯错误:
Traceback (most recent call last):
File "tfidf.py", line 16, in <module>
tokens = get_tokens()
File "tfidf.py", line 12, in get_tokens
no_punctuation = lowers.translate(None, string.punctuation)
TypeError: translate() takes exactly one argument (2 given)
【问题讨论】:
-
这些令牌似乎以 LTR 标记 (
u'\u200e') 和 RTL 标记 (u'\u200f') 开头,编码为 UTF-8。 (我不知道为什么,但似乎你需要做的就是把它们拿出来。)你应该确定你的文件是什么编码的(就像我说的,看起来它可能是 UTF-8 ) 并适当解码。然后根据需要去掉这些字符。 -
我回答了第一个问题(UnicodeWarning)。我建议您为此打开第二个问题:“TypeError:translate() 只采用一个参数(给定 2 个)”