【发布时间】:2016-01-15 17:49:38
【问题描述】:
我正在尝试将字典存储为具有 utf-8 编码的 json 文档,但我似乎做错了什么,无法弄清楚是什么。我已经在下面发布了堆栈跟踪和函数。
def parse_contents(res_dict, file):
content_payload = res_dict['parse']['wikitext']['*']
sections_payload = res_dict['parse']['sections']
db = {}
#parse_captures = ("Owner", "Description", "Usage", "Examples", "Options", "Misc.")
def now_next_iter(iterable):
import itertools
a, b = itertools.tee(sections_payload)
next(b, None)
return itertools.izip(a, b)
def remove_tags(text):
import re
return re.sub('<[^<]+?>', '', text)
for cur, nxt in now_next_iter(sections_payload):
if cur['toclevel'] == 2:
head = cur['line']
db[head] = {}
elif cur['toclevel'] == 3:
line = cur['line']
ibo = cur['byteoffset']
fbo = nxt['byteoffset']
content = remove_tags(content_payload[ibo:fbo])
db[head][line] = content #.encode('utf-8')
with io.open(file, 'w', encoding='utf8') as json_db:
s = json.dumps( db, sort_keys=True, indent=4,
separators=(',', ': '))
json_db.write(s.encode('utf-8'))
尝试 1:
将打印到文件更改为:
with io.open(file, 'w', encoding='utf8') as json_db:
s = json.dumps( db, sort_keys=True, indent=4,
ensure_ascii=False, encoding='UTF8', separators=(',', ': '))
s = s.encode('utf-8')
json_db.write(s)
【问题讨论】: