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]))
首先 這兩個字符串長度不相等, \"
是一個字符, \\
也是一個字符
你可以用 len()
查看。
然后關(guān)于字符串什么的問題,最好說明 python 的版本
maketrans
參數(shù)長度不相等
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 的運行結(jié)果