【问题标题】:TypeError: maketrans() takes exactly 2 arguments (3 given)类型错误:maketrans() 正好接受 2 个参数(给定 3 个)
【发布时间】:2019-01-15 16:33:33
【问题描述】:

以下代码改编自网站,用于从单词中删除标点符号。

import string    
filename = 'some_file.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
# split the text into words
words = text.split()

table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in words]
print(stripped[:100])

错误是"TypeError: maketrans() takes exactly 2 arguments (3 given)"。 我阅读了 Python 文档,其中说明了 maketrans() 具有 1、2 或 3 个参数的选项。 docs.python.org 说:“如果有第三个参数,它必须是一个字符串,其字符将在结果中映射到 None”。 我正在使用 Python 2。有什么办法可以清除错误吗?

【问题讨论】:

  • 如果您使用的是 Python 2,它将是 string.maketrans,它只需要两个参数。
  • 我阅读了 Python 文档,其中说明了 maketrans() 具有 1、2 或 3 个参数的选项。 -- 你能否提供一个链接到你阅读的地方?
  • 我试过你的代码它在 python 3 中没有产生任何错误
  • 同意@khelwood,python2不支持3参数maketrans函数

标签: python string python-2.x


【解决方案1】:

我认为您将 python3.1 文档(在“如果有第三个参数,它......”语句中提到了。)与 Python2。根据 python2 文档 - https://docs.python.org/2/library/string.html,它不能有 3 个参数。

但如果你想实现有第三个参数的功能(将一组字符映射到无),你可以通过将字符串添加到translate来实现,

stripped = [w.translate(table, string.punctuation) for w in words]

【讨论】:

  • 现在我使用的是 Python 3.4,它正在产生错误 type object 'str' has no attribute 'maketrans'
  • 我卸载了 Python 和 Anaconda,并用 Python 3.6 重新安装了整个 Anaconda3。现在它可以正常工作了。谢谢大家。
猜你喜欢
  • 2018-09-12
  • 2015-06-17
  • 2015-07-03
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 2021-07-26
  • 2013-10-29
相关资源
最近更新 更多