Python 将 unicode 字符更改为实体的程序

Python program to change unicode characters to entities

这是一个将 unicode 符号更改为文件 x.input 中各自实体的程序,输出应放在 [=26 中=]。但是,程序不会这样做,只会创建文件的副本。

我 Python27 和 35 都显示这个问题,平台是 Win 7。

我哪里错了?请帮忙。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#import io

f1 = open('x.input').read()
f2 = open('y.output','w')
for line in f1:
    x = line.replace('“', '“')
    f2.write(x)
#f1.close()
f2.close()

整个程序截图: Actual program with the double quote which is creating issues

这个问题有点棘手,你有一个来自文档的 copy/paste 错误,其中字符“(ord 226)不是你期望的”(ord 34)(注意它们是相似的,但是略有不同)。您很可能从 Word 文档中复制了这个示例。

只需用正确的字符替换此字符,您的程序就会运行。结果应该是 (copy/paste from here so you get the correct char):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#import io

f1 = open('x.input').read()
f2 = open('y.output','w')
for line in f1:
    x = line.replace(ord(34), '“')
    f2.write(x)
f1.close()
f2.close()

即使不需要(程序结束时文件将关闭),好公民也会关闭 f1。

注意:编辑是为了使解决方案更清晰,看看如何更改替换行。