【发布时间】:2014-06-04 05:50:34
【问题描述】:
我有以下代码
import nltk, os, json, csv, string, cPickle
from scipy.stats import scoreatpercentile
lmtzr = nltk.stem.wordnet.WordNetLemmatizer()
def sanitize(wordList):
answer = [word.translate(None, string.punctuation) for word in wordList]
answer = [lmtzr.lemmatize(word.lower()) for word in answer]
return answer
words = []
for filename in json_list:
words.extend([sanitize(nltk.word_tokenize(' '.join([tweet['text']
for tweet in json.load(open(filename,READ))])))])
我在编写时已在单独的 testing.py 文件中测试了第 2-4 行
import nltk, os, json, csv, string, cPickle
from scipy.stats import scoreatpercentile
wordList= ['\'the', 'the', '"the']
print wordList
wordList2 = [word.translate(None, string.punctuation) for word in wordList]
print wordList2
answer = [lmtzr.lemmatize(word.lower()) for word in wordList2]
print answer
freq = nltk.FreqDist(wordList2)
print freq
命令提示符返回 ['the','the','the'],这就是我想要的(删除标点符号)。
但是,当我将完全相同的代码放在不同的文件中时,python 返回一个 TypeError 说明
File "foo.py", line 8, in <module>
for tweet in json.load(open(filename, READ))])))])
File "foo.py", line 2, in sanitize
answer = [word.translate(None, string.punctuation) for word in wordList]
TypeError: translate() takes exactly one argument (2 given)
json_list 是所有文件路径的列表(我打印并检查此列表是否有效)。我对这个 TypeError 感到困惑,因为当我只是在不同的文件中测试它时,一切都运行良好。
【问题讨论】:
-
可能会发生这种情况,因为此文件中使用了另一种编码(例如 utf8),translate 函数只获取一个参数。我不确定,但这可能吗?您可以通过为每种情况打印 type(wordList) 来检查这一点。
-
你能展示你的导入语句吗?也许您在不知不觉中导入了翻译功能。遇到异常时尝试“打印翻译”并查看它来自哪个模块
-
@Spaceghost,导入语句为:
import nltk, os, json, csv, string, cPicklefrom scipy.stats import scoreatpercentile (2 separate lines) -
即使在添加导入后,您在第二个文件中的示例代码也不会运行,因为您遗漏了创建 lmtzr 的代码。
-
如上所示,您的代码不完整。没有其他人可以使用它并运行它来查看它的作用。