Ho il seguente codicestr.translate dà TypeError - Tradurre accetta un argomento (2 dato), ha lavorato in Python 2
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))])))])
ho testato le linee 2-4 in un file separato quando testing.py ho scritto
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
e il comando restituisce prompt [ 'la', 'la', 'il'], che è quello che volevo (la rimozione di punteggiatura).
Tuttavia, quando ho messo il codice esattamente lo stesso in un file diverso, python restituisce un TypeError affermando che
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 è una lista di tutti i percorsi dei file (ho stampato e verificare che questa lista è valida). Sono confuso su questo TypeError perché tutto funziona perfettamente quando sto testandolo in un file diverso.
Forse questo avviene perché un'altra codifica (utf8 per esempio) è usato in questo file, per cui la funzione translate ottiene solo un argomento. Non sono sicuro, ma è possibile? È possibile controllare questo stampando il tipo (lista di parole) per ogni caso. – Thorben
Puoi mostrare le istruzioni di importazione? Forse c'è una funzione di traduzione che stai inconsapevolmente importando. Prova "print translate" quando ottieni l'eccezione e vedi quale modulo proviene da – Spaceghost
@Spaceghost, le istruzioni di importazione sono: 'import nltk, os, json, csv, string, cPickle'' da scipy.stats import scoreatpercentile (2 righe separate) ' – carebear