尝试在 Python 3.5.2 shell 中运行命令时收到以下错误:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit
(Intel)] on win32 Type "copyright", "credits" or "license()" for more information.
>>> folder = 'C:/users/kdotz/desktop'
>>> f = open(folder + '/genesis.txt', 'r')
>>> import operator, time, string
>>> start=time.time()
>>> genesis = {}
>>> for line in f:
line=line.split()
for word in line:
word = word.lower()
new_word=word.translate(string.maketrans("",""), string.punctutation)
if new_word in genesis:
genesis[new_word]+=1
else:
genesis[new_word]=1
错误:
Traceback (most recent call last):
File "<pyshell#15>", line 5, in <module>
new_word=word.translate(string.maketrans("",""), string.punctutation)
AttributeError: module 'string' has no attribute 'maketrans'
我做错了什么?我在代码顶部导入字符串。预先感谢您的帮助!
maketrans
已弃用,取而代之的是新的静态方法
函数已弃用,并被新的静态方法string.maketrans()
和bytes.maketrans()
取代。此更改解决了bytearray.maketrans()
模块支持哪些类型的混乱。现在,string
、str
和bytes
每个都有自己的bytearray
和maketrans
方法以及适当类型的中间转换表。translate
每当遇到此类问题时,您可以使用
dir()
来验证:
>>> import string
>>>
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
>>>
如您所见,上面的结果列表中没有
maketrans
。
Py 3.9:
"abcdef".translate(str.maketrans('def', 'ghi'))
你也可以这样做
translator = str.maketrans('', '', string.punctuation)
result = input_str.translate(translator)