7

我正在使用我使用 pip 在 vi​​rtulaenv 中使用 python 3.4 安装的 petl 包。当我试图测试在 python shell 中是否正确安装了 petl 包时,我已经这样做来检查

$ 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 包,那么为什么它会给出导入错误。

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

4

4 回答 4

18

在 Python2 中,maketrans是一个函数属于string模块。然而在 Python3 中,maketrans是一个静态方法str类型。

于 2014-12-18T06:02:41.723 回答
9

因为我正在寻找它在 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)
于 2015-08-16T18:02:34.793 回答
8

使用str调用 maketrans

LETTERS = 'abcdefghijklmnopqrstuvwxyz'
NUMBERS = '22233344455566677778889999'
## translate a-z char to phone digits
TRANS = str.maketrans(LETTERS, NUMBERS)
于 2018-09-02T19:44:24.747 回答
2

更新: petl >= 1.0支持 Python 3.4


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

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

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

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

  1. 使用除petl.
  2. 使用 Python 2.7 进行petl工作。
  3. 帮忙移植一下。

* 实际上,在 3.0 中,它仍然存在,但仅适用于bytes对象。在 3.1 中,maketranstranslate方法添加到bytesand bytearray,相当于 on 的方法str,并且string不推荐使用这些功能,然后在 3.2 或 3.3 中将它们删除。

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

于 2014-12-18T06:38:54.990 回答