python - “str”对象没有属性“maketrans”
问题描述
我希望以不带标点符号的小写形式返回文件中的单词。
尽管有目录str
,bytes
但我无法在我的代码中导入其中任何一个而不会出现导入错误。即使 python 解释器说“name 'string' is not defined”,导入字符串仍然有效
def text_to_words(the_text):
""" return a list of words with all punctuation removed,
and all in lowercase.
"""
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
"abcdefghijklmnopqrstuvwxyz ")
# Translate the text now.
cleaned_text = the_text.translate(my_substitutions)
wds = cleaned_text.split()
return wds
这引发了名义上的错误,而不是翻译。
解决方案
在python 2.x中你必须先导入maketrans
,它在string
模块中:
from string import maketrans
然后更改创建翻译表的行:
my_substitutions = maketrans( ... )
在python 3.x maketrans
中已经定义了,str
所以你不必导入它。
您可以随时检查可用的方法:
dir(str)
推荐阅读
- c# - 需要通过 IIS 应用程序访问 Google Drive V3 - 不使用 MVC
- reactjs - 如何使用 webpack 和 typescript 将 npm 模块 css 导入为全局?
- oop - 数值模拟的函数式编程
- javascript - 在基于 XML 的 Web 应用程序中包含导致 XML 解析错误的库
- javascript - 获取对象数组内数组的累积长度
- python - Django 在模板中向特定用户显示最新的电子邮件
- python - 在 python 中,如何为其中一列中列表的每个元素创建单独的行?
- r - 如果在 purrr 语言中不存在列,则添加列
- c++11 - 如果 C++ 中有引用参数,如何复制函数的参数?
- python - 为什么 pandas 会删除重复数据?