【发布时间】: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