首页 > 解决方案 > “str”对象没有属性“maketrans”

问题描述

我希望以不带标点符号的小写形式返回文件中的单词。

尽管有目录strbytes但我无法在我的代码中导入其中任何一个而不会出现导入错误。即使 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

这引发了名义上的错误,而不是翻译。

标签: pythonstringpython-2.x

解决方案


python 2.x中你必须先导入maketrans,它在string模块中:

from string import maketrans

然后更改创建翻译表的行:

my_substitutions = maketrans( ... )

python 3.x maketrans中已经定义了,str所以你不必导入它。

您可以随时检查可用的方法:

dir(str) 

推荐阅读