2016-11-23 76 views
1

我收到試圖運行在Python 3.5.2外殼命令時,下面的錯誤:的Python AttributeError的:模塊「串」有沒有屬性「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' 

我在做什麼錯誤?我在代碼的頂部導入字符串。先謝謝您的幫助!

+1

在Python 3中'maketrans'是'str'的​​一種方法。 – vaultah

回答

1

maketrans是有利於新的靜態方法

過時

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.

您可以使用dir()驗證,只要你有這樣的問題:

>>> 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'] 
>>> 

正如你所看到的,有沒有maketrans在上面的結果列表中。

+0

我現在得到的錯誤是: '>>>在F線:) \t線= line.split( \t於行字: \t \t字= word.lower() \t \t new_word = word.translate(str.maketrans( 「」, 「」),string.punctuation) \t \t如果new_word在成因: \t \t \t成因[new_word] + = 1 \t \t否則: \t \t個\t成因[new_word] = 1' \t \t \t'回溯(最近最後調用): 文件 「」,第5行,在 new_word = word.translate(str.maketrans( 「」, 「」 ),string.punctuation) TypeError:translate()只需要一個參數(給出2)' –

+0

你需要刪除'string.punctuation' – ettanany

+1

在這裏檢查'str.translate()'文檔https://docs.python。 org/3/library/stdtypes.html#str.translate – ettanany

相關問題