2016-11-23 2 views
1

Je reçois l'erreur ci-dessous lorsque vous essayez d'exécuter une commande shell dans Python 3.5.2:Python AttributeError: Module « string » n'a pas d'attribut « maketrans »

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit  
(Intel)] on win32 Type "copyright", "credits" or "license()" for more information. 

>>> folder = 'C:/users/kdotz/desktop' 
>>> f = open(folder + '/genesis.txt', 'r') 
>>> import operator, time, string 
>>> start=time.time() 
>>> genesis = {} 
>>> for line in f: 
line=line.split() 
for word in line: 
    word = word.lower() 
    new_word=word.translate(string.maketrans("",""), string.punctutation) 
    if new_word in genesis: 
     genesis[new_word]+=1 
    else: 
     genesis[new_word]=1 

Traceback (most recent call last): 
    File "<pyshell#15>", line 5, in <module> 
new_word=word.translate(string.maketrans("",""), string.punctutation) 
AttributeError: module 'string' has no attribute 'maketrans' 

Qu'est-ce que je fais mal? J'importe la chaîne en haut du code. Merci d'avance pour l'aide!

+1

En Python 3 'maketrans' est une méthode de' str'. – vaultah

Répondre

1

maketrans est délaissé au profit de nouvelles méthodes statiques

The string.maketrans() function is deprecated and is replaced by new static methods, bytes.maketrans() and bytearray.maketrans(). This change solves the confusion around which types were supported by the string module. Now, str, bytes, and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.

Vous pouvez utiliser dir() pour vérifier que chaque fois que vous avez ce genre de question:

>>> import string 
>>> 
>>> dir(string) 
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace'] 
>>> 

Comme vous pouvez le voir, il n'y a maketrans dans la liste résultante ci-dessus.

+0

L'erreur que je reçois est maintenant: '>>> pour la ligne à f: \t ligne = line.split() \t pour mot en ligne: \t \t mot = word.lower() \t \t new_word = word.translate (str.maketrans ("", ""), string.punctuation) \t \t si new_word dans la genèse: \t \t \t genèse [new_word] + = 1 \t \t autre: \t \t \t genèse [new_word] = 1' \t \t \t 'retraçage (le plus récent appel dernier): fichier "", ligne 5, dans new_word = word.translate (str.maketrans ("", ""), string.punctuation) TypeError: translate() prend exactement un argument (2 donnés) ' –

+0

Vous devez supprimer' string.punctuation' – ettanany

+1

Vérifiez la documentation 'str.translate()' ici https: //docs.python. org/3/library/stdtypes.html # str.translate – ettanany