【问题标题】:Python AttributeError: module 'string' has no attribute 'maketrans'Python AttributeError:模块'string'没有属性'maketrans'
【发布时间】:2017-04-07 18:58:20
【问题描述】:

尝试在 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'

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

【问题讨论】:

  • 在 Python 3 中 maketransstr 的方法。

标签: python python-3.x attributeerror


【解决方案1】:

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

【讨论】:

  • 我现在得到的错误是:&gt;&gt;&gt; for line in f: line=line.split() for word in line: word=word.lower() new_word = word.translate(str.maketrans("",""), string.punctuation) if new_word in genesis: genesis[new_word]+=1 else: genesis[new_word]=1Traceback (most recent call last): File "&lt;pyshell#67&gt;", line 5, in &lt;module&gt; new_word = word.translate(str.maketrans("",""), string.punctuation) TypeError: translate() takes exactly one argument (2 given)
  • 你需要删除string.punctuation
  • 在此处查看str.translate() 文档docs.python.org/3/library/stdtypes.html#str.translate
  • 谢谢大家!
【解决方案2】:

Py 3.9:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2023-04-06
    • 2018-06-16
    • 2015-03-09
    • 2020-10-18
    • 2016-12-26
    相关资源
    最近更新 更多