【问题标题】:string.translate() does not accept 2 args [duplicate]string.translate() 不接受 2 个参数 [重复]
【发布时间】:2023-03-16 04:00:02
【问题描述】:

我看过几个答案 Best way to strip punctuation from a string in Python 但这些似乎都没有解决我的问题。我正在尝试使用 string.translate() 从字符串中去除标点符号。

当我运行代码时:

import string
s = "This. has? punctuation," 
noPunct = s.translate(s.maketrans("",""), string.punctuation)

我明白了:

TypeError: translate() takes exactly one argument (2 given)

这可能是我使用的 python 版本的问题吗?我正在使用 python 3.5.4 与 nltk 兼容。否则我很难过。任何帮助,将不胜感激。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    str.translate 的 Python 3 接口使用映射。用str.maketrans做一个:

    >>> import string
    >>> table = str.maketrans({}.fromkeys(string.punctuation))
    >>> "This. has? punctuation,".translate(table)
    'This has punctuation'
    

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      您使用的是 Python 2.x 代码,但运行的是 Python 3.x。向下滚动链接的问题以查看如何在 Python 3.x 中执行此操作:

      s.translate(mapping)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2018-11-29
        • 1970-01-01
        • 2013-11-18
        • 2018-06-24
        • 2019-04-06
        • 2021-10-16
        相关资源
        最近更新 更多