我正在尝试从拆分字符串创建一个有序的字典。如何保持分割字符串的顺序?抱歉,我最初的例子令人困惑,并且与有序字典的概念相矛盾。这是一个不同的问题,但我不确定如何分割字符串。
我的示例文件"practice_split.txt"如下所示:
§1 text for chapter 1 §2 text for chapter 2 §3 text for chapter 3
我希望我的有序字典看起来像:
OrderedDict([('§1', 'text for chapter 1'), ('§2', 'text for chapter 2'), ('§3', 'text for chapter 3')])
代替:
OrderedDict([('1 text for chapter 1 ', 'xc2xa7'), ('xc2xa7', '3 text for chapter 3'), ('2 text for chapter 2 ', 'xc2xa7')])
这是我的代码:
# -*- coding: utf-8 -*
import codecs
import collections
import re
with codecs.open('practice_split.txt', mode='r', encoding='utf-8') as document:
o_dict = collections.OrderedDict()
for line in document:
conv = line.encode('utf-8')
a = re.split('(§)', conv)
a = a[1:len(a)]
for i in range(1, len(a) - 1):
o_dict[a[i]] = a[i+1]
print o_dict
谢谢!
从我对你的代码的理解,你的循环是不正确的。您需要第一个具有第一个文本条目的§
。您还希望跳过作为字典键的§
元素,因此需要对循环执行步骤2。最后,您可能希望去掉文本开头/结尾的空格。
for i in range(1, len(a), 2):
o_dict["{}{}".format(a[i - 1], i / 2 + 1)] = a[i].strip()
print o_dict
for k, v in o_dict.iteritems():
print k.decode('utf-8'), v
输出:OrderedDict([('xc2xa71', 'text for chapter 1'), ('xc2xa72', 'text for chapter 2'), ('xc2xa73', 'text for chapter 3')])
§1 text for chapter 1
§2 text for chapter 2
§3 text for chapter 3
编辑:我改变了我的代码,以反映对OPs问题的编辑。
问题不在于OrderedDict,而在于您的for
循环。循环执行以下操作:
将' text for chapter 1 '指向字典中的'xc2xa7' #
指向'xc2xa7'到' text for chapter 2 ' #这将被覆盖
将' text for chapter 2 '指向字典中的'xc2xa7' #,就像
将'xc2xa7'指向' text for chapter 3 ' #这将覆盖第二个条目,因此它将在第二个位置结束
不确定您实际希望字典包含什么,或者我建议使用一些代码....