python3.x - Comment utiliser maketrans en python dans des fichiers utf-8
过去多啦不再A梦
过去多啦不再A梦 2017-05-18 10:58:56
0
1
704

J'ai écrit un fichier pour traiter le texte, qui consiste à remplacer tous les symboles du texte par des espaces. Utilisez maketrans et traduisez en python. C'est normal lors de l'utilisation de fichiers encodés ASCII, mais lors de l'utilisation de fichiers UTF-8, une erreur est signalée, indiquant que les paramètres dans maketrans ne sont pas de longueur égale, mais ils ont évidemment la même longueur :

Fichier "/Users/lgq/Desktop/p3.py", ligne 10, dans text_to_words

"abcdefghijklmnopqrstuvwxyz                                                   ") 

ValueError : les deux premiers arguments maketrans doivent avoir la même longueur

J'ai vérifié et il a été dit que maketrans ne pouvait pas être utilisé sous utf-8. Alors, comment dois-je remplacer les caractères sous utf-8 ?

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梦

répondre à tous(1)
滿天的星座

Tout d'abord, les longueurs de ces deux chaînes ne sont pas égales. " est un caractère, et \ est également un caractère
Vous pouvez utiliser len () Vérifiez.
Quant à la question des chaînes, il est préférable d'indiquer la version de python" 是一个字符, \ 也是一个字符
你可以用 len() 查看。
然后关于字符串什么的问题,最好说明 python 的版本

maketrans.

Les longueurs des paramètres maketrans ne sont pas égales

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

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!\"#$%&()*+,-./:;<=>?@[]^_`{|}~\'\测试')
sortie

['abcdefghijklmnopqrstuvwxyz', '\xe6\xb5\x8b\xe8\xaf\x95']
C'est le résultat de l'exécution de python2🎜
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!