到目前为止,我设法使此代码运行:
# -*- coding: utf-8 -*-
import sys,os
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def window():
root = Tk()
root.withdraw()
ftypes = [('Subtitle file',"*.srt"),('Subtitle file',"*.sub"),('Text file',"*.txt")]
ttl = "Open"
dir1 = 'D:\\ovdjetorent'
root.fileName = askopenfilename(filetypes = ftypes, initialdir = dir1, title = ttl)
TitlFajlPath = str(root.fileName)
return TitlFajlPath
def radnja_sa_fajlom():
TitlFajlPath = window()
print(TitlFajlPath)
TitlFajl = open(TitlFajlPath, 'r+')
TitlContent = TitlFajl.read()
TitlContent = TitlContent.replace('æ','ć').replace('è','č').replace('ð','đ').replace('Æ','Ć').replace('È','Č')
TitlFajl.write(TitlContent)
print(TitlContent)
input('Press ENTER to exit')
radnja_sa_fajlom()
函数window()只是获取将要使用的文件的字幕文件路径的一种好方法。函数radnja_sa_fajlom()使用 os.open()函数打开该文件,它更改了错误字符,但是当我尝试保存该文件时,它失败并显示:
UnicodeEncodeError: 'charmap' codec can't encode character '\u0107' in position 608: character maps to <undefined>
我尝试使用编解码器和io模块,但是它们忽略了换行符,结果文字混乱。
我该怎么做才能将替换后的内容写到同一文件中?以UTF-8编码,没有任何问题?
谢谢:)