【问题标题】:Maketrans not working for petl with python3.4Maketrans 不适用于带有 python3.4 的 petl
【发布时间】:2014-12-18 05:38:58
【问题描述】:

我正在使用我在 virtulaenv 中使用 pip 和 python 3.4 安装的 petl 包。当我试图测试petl包是否在python shell中正确安装时 我这样做是为了检查

$ python 
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from petl import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/.env/lib/python3.4/site-packages/petl/__init__.py", line 10, in <module>
    from petl.util import header, fieldnames, data, records, rowcount, look, see, \
  File "/home/user/.env/lib/python3.4/site-packages/petl/util.py", line 14, in <module>
    from string import maketrans
ImportError: cannot import name 'maketrans'
>>>

我试图检查我运行的字符串包中是否存在maketrans

>>> from string import maketrans
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'maketrans'
>>> 

发现默认python字符串包没有这个。我不确定为什么 petl 包在其依赖项中没有提及它而使用它,如果它是默认的 python 包,那么为什么它会给出导入错误。

不知道发生了什么,请任何人帮忙

【问题讨论】:

    标签: python python-3.x petl


    【解决方案1】:

    在 Python2 中,maketrans 是属于 string 模块的函数。但是在 Python3 中,maketransstr 类型的静态方法。

    【讨论】:

      【解决方案2】:

      因为我一直在寻找它在 python 3.4 中如何工作的清晰示例,所以我发布了我发现的内容:

      #in py2 you need to "from string import maketrans" 
      table = "".maketrans('cs', 'kz')
      #py2 table = maketrans('cs', 'kz')
      len(table)
      #in py2 you will get **len(table) = 256 in py3.4 len(table) = 2**
      sentence = "cause koala is causing trouble"
      sentence.translate(table)
      

      【讨论】:

        【解决方案3】:

        使用 str 调用 maketrans

        LETTERS = 'abcdefghijklmnopqrstuvwxyz'
        NUMBERS = '22233344455566677778889999'
        ## translate a-z char to phone digits
        TRANS = str.maketrans(LETTERS, NUMBERS)
        

        【讨论】:

          【解决方案4】:

          更新: petl &gt;= 1.0 supports Python 3.4.


          显然petl 不适用于 Python 3.x。

          这个特定的错误是因为 Python 2.x string.maketrans 函数在 3.x 中不存在。* 但是如果你过去了,你会发现很多其他错误。

          虽然 PyPI 条目没有列出支持的版本(它确实应该列出),但一个快速的谷歌出现了 Issue #240,以添加 Python 3 支持,该支持自 2014 年 8 月 26 日以来一直在积压中。还有一个 @987654328 @pass over source 显示数百个问题。**

          那么,你如何解决这个问题?

          1. 使用petl以外的其他内容。
          2. 将 Python 2.7 用于您的 petl 工作。
          3. 帮助移植它。

          * 实际上,在 3.0 中,它仍然存在,但仅适用于 bytes 对象。在 3.1 中,maketranstranslate 方法被添加到 bytesbytearray 中,等同于 str 上的方法,并且 string 函数被弃用,然后在 3.2 或 3.3 中它们被删除。

          ** 其中一些问题使用了在 2.6 或 2.7 中已弃用的东西,这很奇怪,因为 petl 最初只在 2.7 中有效,后来被移植到 2.6 中也有效。子>

          【讨论】:

            猜你喜欢
            • 2014-07-30
            • 1970-01-01
            • 2015-04-04
            • 2015-07-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多