【问题标题】:What does "table" in the string.translate function mean?string.translate 函数中的“table”是什么意思?
【发布时间】:2014-01-29 02:32:32
【问题描述】:

通过string.translate 函数显示:

从 s 中删除 deletechars 中的所有字符(如果存在),然后使用 table 翻译字符,table 必须是一个 256 字符的字符串,给出每个字符值的翻译,按其序号索引。如果 table 为 None,则只执行字符删除步骤。

  • table 在这里是什么意思?可以是包含映射的dict 吗?
  • “必须是 256 个字符的字符串” 是什么意思?
  • 表格可以手动或通过自定义函数代替string.maketrans吗?

我尝试使用该功能(尝试如下)只是为了看看它是如何工作的,但未能成功使用它。

>>> "abcabc".translate("abcabc",{ord("a"): "d", ord("c"): "x"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: translation table must be 256 characters long
>>> "abcabc".translate({ord("a"): ord("d"), ord("c"): ord("x")}, "b")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

>>> "abc".translate({"a": "d", "c": "x"}, ["b"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

我在这里错过了什么?

【问题讨论】:

    标签: python string python-2.7


    【解决方案1】:

    这取决于您使用的 Python 版本。

    在 Python 2.x 中。该表是 256 个字符的字符串。可以使用string.maketrans创建:

    >>> import string
    >>> tbl = string.maketrans('ac', 'dx')
    >>> "abcabc".translate(tbl)
    'dbxdbx'
    

    在 Python 3.x 中,该表是 unicode 序数到 unicode 字符的映射。

    >>> "abcabc".translate({ord('a'): 'd', ord('c'): 'x'})
    'dbxdbx'
    

    【讨论】:

    • Python 2 unicode.translate() 的行为与 Python 3 中的 str.translate() 完全相同。那是因为您有超过 256 个可能的值需要翻译。相反,bytes.translate() 的工作方式与 Python 2 str.translate() 完全相同。所以它不依赖于 Python 版本,它依赖于对象类型; Unicode 与字节串。
    【解决方案2】:

    table必须是256个字符的字符串; str.translate() 方法使用此表将字节值(0 到 255 之间的数字)映射到新字符;例如任何字符 'a'(整数值为 97 的字节)都将替换为表中的第 98 个字符。

    您真的想引用str.translate() documentation 来了解这一切,而不是string.translate() 函数;后者的文档并不完整。

    您可以使用string.maketrans 函数构建一个;你给它just你想用替换它们的字符替换的字符;对于你的例子,那就是:

    >>> import string
    >>> table = string.maketrans('ac', 'cx')
    >>> len(table)
    256
    >>> table[97]
    'c'
    >>> 'abcabc'.translate(table, 'b')
    'cxcx'
    

    第二个参数也应该是一个字符串。

    您似乎已经阅读了 unicode.translate() 方法的文档;行为发生了变化,您确实必须为unicode.translate() 传递字典。由于 Python 2 的 unicode 类型是 Python 3 中的 str 类型,这也是您在 Python 3 中使用 str.translate() 的方式(其中 bytes.translate() 与上述行为匹配)。

    【讨论】:

      【解决方案3】:

      要翻译文本,不使用字典 {ordinal: char},而是使用字典 {char: char}(例如 {'a': 'X', 'J': 'y', ...}:

      text.translate({ord(k):dictionary[k] for k in dictionary})
      

      【讨论】:

        猜你喜欢
        • 2013-11-21
        • 2016-01-22
        • 1970-01-01
        • 2015-09-25
        • 1970-01-01
        • 2013-03-30
        • 1970-01-01
        • 2011-01-21
        • 2015-01-12
        相关资源
        最近更新 更多