【发布时间】:2020-09-03 19:54:05
【问题描述】:
所以我有一个代码,它接受一个 .txt 文件并将其作为字符串添加到变量中。
然后,我尝试在其上使用 .replace() 将字符“ó”更改为“o”,但它不起作用!控制台打印同样的东西。
代码:
def normalize(filename):
#Ignores errors because I get the .txt from my WhatsApp conversations and emojis raise an error.
#File says: "Es una rubrica de evaluación." (among many emojis)
txt_raw = open(filename, "r", errors="ignore")
txt_read = txt_raw.read()
#Here, only the "o" is replaced. In the real code, I use a for loop to iterate through all chrs.
rem_accent_txt = txt_read.replace("ó", "o")
print(rem_accent_txt)
return
预期输出:
"Es una rubrica de evaluacion."
电流输出:
"Es una rubrica de evaluación."
它不会打印错误或任何东西,它只是按原样打印。
我认为问题在于字符串来自文件这一事实,因为当我只是创建一个字符串并使用代码时,它确实可以工作,但是当我从文件中获取字符串时它就不起作用了。
编辑:解决方案!
感谢@juanpa.arrivillaga 和@das-g 我想出了这个解决方案:
from unidecode import unidecode
def get_txt(filename):
txt_raw = open(filename, "r", encoding="utf8")
txt_read = txt_raw.read()
txt_decode = unidecode(txt_read)
print(txt_decode)
return txt_decode
【问题讨论】:
-
你用的是什么版本的python?
-
看起来像 unicode 问题 - stackoverflow.com/questions/13093727/…
-
我使用 3.8.3 64 位。我试过 unicode,但它弄乱了字符。例如,它会输出类似
evaluaciAn。 -
"#Ignores 错误,因为我从我的 WhatsApp 对话中获取了 .txt,并且表情符号引发了错误。"您应该尝试使用正确的编码。
-
问题可能出在您创建文件的时候。文本文件是如何创建的?