【发布时间】:2013-11-28 16:50:05
【问题描述】:
两个文件。一个有损坏的数据,另一个有修复。破碎:
ID 0
T5 rat cake
~EOR~
ID 1
T1 wrong segg
T2 wrong nacob
T4 rat tart
~EOR~
ID 3
T5 rat pudding
~EOR~
ID 4
T1 wrong sausag
T2 wrong mspa
T3 strawberry tart
~EOR~
ID 6
T5 with some rat in it
~EOR~
修复:
ID 1
T1 eggs
T2 bacon
~EOR~
ID 4
T1 sausage
T2 spam
T4 bereft of loif
~EOR~
EOR 表示记录结束。请注意,Broken 文件比修复文件包含更多记录,修复文件具有要修复的标签(T1、T2 等是标签)和要添加的标签。这段代码完全按照它应该做的:
# foobar.py
import codecs
source = 'foo.dat'
target = 'bar.dat'
result = 'result.dat'
with codecs.open(source, 'r', 'utf-8_sig') as s, \
codecs.open(target, 'r', 'utf-8_sig') as t, \
codecs.open(result, 'w', 'utf-8_sig') as u:
sID = ST1 = sT2 = sT4 = ''
RecordFound = False
# get source data, record by record
for sline in s:
if sline.startswith('ID '):
sID = sline
if sline.startswith('T1 '):
sT1 = sline
if sline.startswith('T2 '):
sT2 = sline
if sline.startswith('T4 '):
sT4 = sline
if sline.startswith('~EOR~'):
for tline in t:
# copy target file lines, replacing when necesary
if tline == sID:
RecordFound = True
if tline.startswith('T1 ') and RecordFound:
tline = sT1
if tline.startswith('T2 ') and RecordFound:
tline = sT2
if tline.startswith('~EOR~') and RecordFound:
if sT4:
tline = sT4 + tline
RecordFound = False
u.write(tline)
break
u.write(tline)
for tline in t:
u.write(tline)
我正在写入一个新文件,因为我不想弄乱其他两个文件。第一个外部 for 循环在修复文件中的最后一条记录处结束。此时,目标文件中仍有记录要写入。这就是最后一个 for 子句的作用。
最后一行隐含地指出了第一个内部 for 循环最后一次中断的地方,这让我很烦。就好像它应该说'for the rest of tline in t'。另一方面,我不知道如何用更少(或不多)的代码行(使用字典和你有什么)来做到这一点。我应该担心吗?
请发表评论。
【问题讨论】:
-
我会创建一个计数器“tPosition”,每次通过相关循环时都会增加该计数器。然后,当你想说“for the rest of tline in t”时,你可以表明你想循环类似:for tline in t[tPosition:]
标签: python for-loop coding-style