Python 使用 translate() 方法时出现类型错误

Python TypeError using the translate() method

我正在尝试在 Python 中构建一个函数,从字符串中提取特定字符,然后 return 将剩余的每个单词放在单独的行中。必须删除撇号 -- 并且缩略语必须分开,后半部分移至新行。

比如我有这句话片段:

", that doesn't mean much to him."

我想删除这些标点符号:

",'."

应该return:

that
doesn
t
mean
much
to
him

这是我写的函数:

def remove_chars(frag, punc):
    if "'" in frag:
        frag = frag.replace("'", " ")

    frag = frag.translate(None, punc)

    frag = frag.split(" ")

    for i in frag:
        print i

remove_chars(", that doesn't mean much to him.", ",'.")

这是我收到的错误:

TypeError: deletions are implemented differently for unicode

在此先感谢您对此的任何帮助。

unicode.translate()方法确实和str.translate()方法不同。它只需要 一个 参数,一个将整数代码点值映射到其他值的字典。要删除,其他值应该是 None.

您可以使用 dict.fromkeys():

轻松创建这样的字典
mapping = dict.fromkeys(map(ord, punc))
frag = frag.translate(mapping)

由于键必须是整数,所以我使用 ord 将字符串 punc 中的每个字符映射到相应的整数代码点。 dict.fromkeys() 然后创建一个包含所有这些整数键的字典,并为每个键赋予默认值 None.

演示:

>>> punc = ",'."
>>> dict.fromkeys(map(ord, punc))
{44: None, 46: None, 39: None}
>>> mapping = dict.fromkeys(map(ord, punc))
>>> u", that doesn't mean much to him.".translate(mapping)
u' that doesnt mean much to him'

我做了更多的研究,最后想出了这个——我认为这是正确的(并且可能是最干净的解决方案):

def remove_chars(frag, punc):

    for i in punc:
        frag = frag.replace(i, ' ')
    for j in frag.split():
        print j


print remove_chars(", that doesn't mean much to him.", ",'.")

如果您看到错误,请告诉我。

以防万一,这个 deletions are implemented differently for unicode 已包含在我的代码中,具有以下规格:

  • Python 2
  • 使用from __future__ import unicode literals
  • 要翻译的字符串是str或bytes
  • 翻译功能写得像mystr.translate(None, ',-()')

这里的问题是字符串 ' ,-()',由于 unicode_literals 导入,它是 unicode。解决方法如下:

from __future__ import unicode_literals

' Any-cleaned string(seriously), string'.translate(None, b',-()')