Heim  >  Fragen und Antworten  >  Hauptteil

python3.x – So verwenden Sie maketrans in Python in UTF-8-Dateien

Ich habe eine Datei zum Verarbeiten von Text geschrieben, die alle Symbole im Text durch Leerzeichen ersetzen soll. Verwenden Sie maketrans und übersetzen Sie in Python. Bei der Verwendung von ASCII-codierten Dateien ist dies normal. Bei der Verwendung von UTF-8-Dateien wird jedoch ein Fehler gemeldet, der darauf hinweist, dass die Parameter in maketrans nicht gleich lang sind, aber offensichtlich die gleiche Länge haben:

Datei „/Users/lgq/Desktop/p3.py“, Zeile 10, in text_to_words

"abcdefghijklmnopqrstuvwxyz                                                   ") 

ValueError: Die ersten beiden maketrans-Argumente müssen die gleiche Länge haben

Ich habe nachgesehen und festgestellt, dass maketrans unter utf-8 nicht verwendet werden kann. Wie soll ich die Zeichen unter utf-8 ersetzen?

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


def get_words_in_book(filename):
    """ Read a book from filename, and return a list of its words."""
    f = open(filename, "r", encoding = "utf-8")
    content = f.read()
    f.close()
    wds = text_to_words(content)
    return wds


book_words = get_words_in_book("alice.txt")
print("There are {0} words in the book, the first 100 are\n{1}".
        format(len(book_words), book_words[:100]))
过去多啦不再A梦过去多啦不再A梦2712 Tage vor718

Antworte allen(1)Ich werde antworten

  • 滿天的星座

    滿天的星座2017-05-18 11:00:56

    首先 这两个字符串长度不相等, \" 是一个字符, \\ 也是一个字符
    你可以用 len() 查看。
    然后关于字符串什么的问题,最好说明 python 的版本

    maketrans 参数长度不相等

     my_substitutions = the_text.maketrans(
            # If you find any of these
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
            # Replace them by these
            "abcdefghijklmnopqrstuvwxyz                                            ")

    测试代码:

    from string import translate, maketrans
    
    def text_to_words(the_text):
        """ 
            Return a list of words with all punctuation removed,
            and all in lowercase.
        """
        my_substitutions = 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
    
    text_to_words('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~\'\\测试')

    output

    ['abcdefghijklmnopqrstuvwxyz', '\xe6\xb5\x8b\xe8\xaf\x95']

    这是 python2 的运行结果

    Antwort
    0
  • StornierenAntwort