Python AttributeError: 模块 'string' 没有属性 'maketrans'。

7

当我尝试在Python 3.5.2 shell中运行命令时,出现以下错误:

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'

我哪里做错了?我在代码顶部导入了string模块。提前感谢您的帮助!

3
在Python 3中,maketransstr的一个方法。 - vaultah
2个回答

8

maketrans已经被废弃,使用新的静态方法代替。

string.maketrans()函数已经被废弃,现在可以使用新的静态方法:bytes.maketrans()bytearray.maketrans()。这种改变解决了关于string模块支持哪些类型的混淆问题。现在,strbytesbytearray都有自己的maketranstranslate方法,并且具有适当类型的中间翻译表。

您可以使用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


1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Krista Marie
3
你需要移除 string.punctuation - ettanany
3
请查看这里的 str.translate() 文档 https://docs.python.org/3/library/stdtypes.html#str.translate - ettanany
谢谢大家! - Krista Marie

8

Py 3.9:

"abcdef".translate(str.maketrans('def', 'ghi'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接