【问题标题】:How to UTF-8 encode and replace text inside txt file?如何对 txt 文件中的文本进行 UTF-8 编码和替换?
【发布时间】:2014-08-24 14:24:31
【问题描述】:

我正在尝试编写一个应用程序,用于打开选定(子)文件夹中的 txt 文件,并将所有字母“ž”替换为字母“š”,并将其保存为 UTF-8 格式。

这是我到目前为止所做的(版本 2 - 见编辑):

import os
import codecs

startIn = os.getcwd()

print()
print("Pregledujem: " + startIn + "\\")
print("-------------------------")

for dirName, subdirList, fileList in os.walk(startIn):
  print()
  print("Trenutna mapa: " + dirName + "\\")
  for fname in fileList:
    if fname.endswith(".srt"):
      fullpath = dirName + "\\" + fname
      print("  Podnapis: " + fname )
      with codecs.open(fullpath, 'r+', "UTF-8-sig") as cursub:
        lines = cursub.read().replace("ž","š")
        cursub.seek(0)
        cursub.write(lines)

编辑

现在替换字母可以正常工作,但我仍然无法弄清楚如何正确编码文件 TO utf-8

当前版本输出如下错误:

UnicodeDecodeError: 'utf-8' 编解码器无法在位置解码字节 0x9a 220: 无效的起始字节

【问题讨论】:

  • 什么不起作用?
  • 哪个版本的 Python?
  • 你正在替换,但你没有写回;当您执行 line.replace 时,它不会写回该行,它只是修改它。您遇到的另一个问题是您打开文件进行写入,这将删除其内容;这意味着line 不会包含您要替换的字母。

标签: python replace utf-8


【解决方案1】:

如果要读写打开r+模式

cursub = codecs.open(filename, 'r+',"utf-8")
lines = cursub.read().replace("š", "ž")
cursub.seek(0)  # go back to start of file
cursub.write(lines) # rewrite updated lines

使用 with 会自动关闭文件:

with codecs.open(filename, 'r+',"utf-8") as cursub: 
    lines = cursub.read().replace("š", "ž")
    cursub.seek(0)
    cursub.write(lines)

【讨论】:

  • 太好了,像现在这样替换作品:) 除了编码保持 ASCII 而不是 UTF-8。有什么建议么? PS 那些投反对票的人是怎么回事?
【解决方案2】:

如果您要编辑(或更确切地说是重写)一个文件,您不应该在写入模式下打开它,因为这样就无法读取它。 要么先将整个文件读入内存,要么先从原始文件读取,然后写入副本(或先复制并从副本中读取,然后重写原始文件)。

【讨论】:

    猜你喜欢
    • 2010-11-30
    • 2017-10-08
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2021-04-08
    • 1970-01-01
    • 2014-02-18
    相关资源
    最近更新 更多