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

2024-05-23 23:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 3.5.2shell中运行命令时,我收到以下错误:

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'

我做错什么了?我在代码顶部导入字符串。提前谢谢你的帮助!


Tags: in命令genesisnewforstringtime错误
1条回答
网友
1楼 · 发布于 2024-05-23 23:00:38

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

相关问题 更多 >