Reputation: 110592
I am writing a file in Chinese:
<locale name="cmn-Hans">
<title>大白鲨 Jaws</title>
<synopsis>由金像奖导演史蒂芬·斯皮尔伯格执导,《大白鲨》树立了紧张悬疑片的标准,并迅速成为一种文化现象,永远改变了观众的电影经验。濒海的艾米提小镇遭到一条危险的大白鲨攻击,镇上的警长(洛伊·薛德)、年轻的海洋生物学家(理查德·瑞佛斯)、老成的鲨鱼猎人(罗伯特·萧)联手展开一场危急的冒险,准备毁灭这只怪兽,免得它再度伤人。令人难忘的配乐带来纯粹的恐惧,《大白鲨》至今仍是电影史上最具影响力、最扣人心弦的冒险电影之一。</synopsis>
</locale>
The file is written using codecs
like so:
new_file = codecs.open(metadata_filepath, 'w', 'utf8')
new_file.write(u'''contents here''')
How would I get the file to look like the actual Chinese characters instead of the unicode characters:
<locale name="cmn-Hans">
<title>大白鲨 Jaws</title>
<synopsis>由金像奖导演史蒂芬·斯皮尔伯格执导,《大白鲨》树立了紧张悬疑片的标准,并迅速成为一种文化现象,永远改变了观众的电影经验。濒海的艾米提小镇遭到一条危险的大白鲨攻击,镇上的警长(洛伊·薛德)、年轻的海洋生物学家(理查德·瑞佛斯)、老成的鲨鱼猎人(罗伯特·萧)联手展开一场危急的冒险,准备毁灭这只怪兽,免得它再度伤人。令人难忘的配乐带来纯粹的恐惧,《大白鲨》至今仍是电影史上最具影响力、最扣人心弦的冒险电影之一。</synopsis>
</locale>
How would I get the file to print the Chinese characters (至今仍) instead of the Unicode representations (490;上) ?
To get the initial contents I am using etree.tostring(...)
from a Chinese xml file.
Upvotes: 0
Views: 137
Reputation: 140886
In Python 2, pass encoding="utf-8"
to ElementTree.tostring
and then open your file in binary mode. In Python 3, you can instead pass encoding="unicode"
to ElementTree.tostring
and then open the file as you are.
Demo (Python 2):
>>> print(ET.tostring(tree, encoding="utf-8"))
<locale name="cmn-Hans">
<title>大白鲨 Jaws</title>
<synopsis>由金像奖导演史蒂芬·斯皮尔伯格执导,《大白鲨》树立了紧张悬疑片的标准,并迅速成为一种文化现象,永远改变了观众的电影经验。濒海的艾米提小镇遭到一条危险的大白鲨攻击,镇上的警长(洛伊·薛德)、年轻的海洋生物学家(理查德·瑞佛斯)、老成的鲨鱼猎人(罗伯特·萧)联手展开一场危急的冒险,准备毁灭这只怪兽,免得它再度伤人。令人难忘的配乐带来纯粹的恐惧,《大白鲨》至今仍是电影史上最具影响力、最扣人心弦的冒险电影之一。</synopsis>
</locale>
>>> print(ET.tostring(tree))
<locale name="cmn-Hans">
<title>大白鲨 Jaws</title>
<synopsis>由金像奖导演史蒂芬·斯皮尔伯格执导,《大白鲨》树立了紧张悬疑片的标准,并迅速成为一种文化现象,永远改变了观众的电影经验。濒海的艾米提小镇遭到一条危险的大白鲨攻击,镇上的警长(洛伊·薛德)、年轻的海洋生物学家(理查德·瑞佛斯)、老成的鲨鱼猎人(罗伯特·萧)联手展开一场危急的冒险,准备毁灭这只怪兽,免得它再度伤人。令人难忘的配乐带来纯粹的恐惧,《大白鲨》至今仍是电影史上最具影响力、最扣人心弦的冒险电影之一。</synopsis>
</locale>
Upvotes: 2