'str'对象没有属性'maketrans'

时间:2019-05-05 17:33:43

标签: python string python-2.x

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

尽管具有目录strbytes,但我无法在我的代码中导入任何一个而没有导入错误。即使python解释器说“未定义名称'string'”,导入字符串仍然有效

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

与翻译相反,这会引发名义错误。

1 个答案:

答案 0 :(得分:1)

python 2.x 中,您必须首先导入News.aggregate([ { "$match": query }, { "$sort": { "date": -1 } }, { "$skip": page * pageLength }, { "$limit": pageLength }, { "$lookup": { "from": "newslikes", "localField": "_id", "foreignField": "article", "as": "likes" }}, { "$project": { "title": 1, "likes": 1, "content": 1, // numLikes: { $size: '$likes' } "userLikeStatus": { "$let": { "vars": { "array": { "$filter": { "input": "$likes", "as": "like", "cond": { "$eq": ["$$like.user", mongoose.Types.ObjectId("5ccf13adcec5e6d84f940417")] } } } }, "in": { "$ifNull": [{ "$arrayElemAt": ["$$array.state", 0] }, "none"] } } } }} ]) ,它在maketrans模块中:

string

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

from string import maketrans

python 3.x 中,my_substitutions = maketrans( ... ) 已经为maketrans定义了,因此您不必导入它。

您始终可以检查哪些方法可用:

str