【问题标题】:How can I use .replace() on a .txt file with accented characters?如何在带有重音字符的 .txt 文件上使用 .replace()?
【发布时间】: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,并且表情符号引发了错误。"您应该尝试使用正确的编码。
  • 问题可能出在您创建文件的时候。文本文件是如何创建的?

标签: python string replace


【解决方案1】:

几乎可以肯定,发生的情况是您有一个未标准化的 unicode 字符串。本质上,有两种方法可以在 unicode 中创建"ó"

>>> combining = 'ó'
>>> composed = 'ó'
>>> len(combining), len(composed)
(2, 1)
>>> list(combining)
['o', '́']
>>> list(composed)
['ó']
>>> import unicodedata
>>> list(map(unicodedata.name, combining))
['LATIN SMALL LETTER O', 'COMBINING ACUTE ACCENT']
>>> list(map(unicodedata.name, composed))
['LATIN SMALL LETTER O WITH ACUTE']

只需标准化你的字符串:

>>> composed == combining
False
>>> composed == unicodedata.normalize("NFC", combining)
True

虽然,退一步说,你真的想去掉重音符号吗?或者你只是想像上面那样规范化为组合?

顺便说一句,您在阅读文本文件时不应忽略错误。您应该使用正确的编码。我怀疑正在发生的事情是您使用不正确的编码编写文本文件,因为您应该能够很好地处理表情符号,它们在 unicode 中没有什么特别的。

>>> emoji = "?"
>>> print(emoji)
?
>>>
>>> unicodedata.name(emoji)
'GRINNING FACE'

【讨论】:

  • 谢谢!按照这个例子以及@das-g 的评论,我想出了解决方案!我将其添加到问题中,谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 2015-02-06
  • 2016-09-21
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
相关资源
最近更新 更多