我从网址导入了一个文本文件,想要处理它。该文件如下所示。有两个“局”和“额外”的实例。我想在第一个“局”实例和第一个“额外”实例之间提取线。我编写的代码提取所有实例。我该如何解决这个问题?
Toss:斯里兰卡裁判:M Erasmus(南非)和NJ Llong (英格兰)电视裁判:S Ravi(印度)比赛裁判:DC Boon (澳大利亚)预备裁判:SD弗莱(澳大利亚)球员 比赛:CJ安德森新西兰局(最多50次)
R M B 4 6 MJ Guptill c Sangakkara b Lakmal
49 94 62 5 0 CJ Anderson c Lakmal b Kulasekara 75 77 46 8 2
+ L Ronchi没有出29 29 19 4 0
附加功能(lb 2,w 8,nb 3)13总计(6个小门,50个过滤,226分钟)331
斯里兰卡局(目标:332从50分开始)R M B 4 6 HDRL Thirimanne b Boult
65 90 60 8 0 RAS Lakmal没有出局
7 21 17 0 0
附加内容(w 10,nb 1)11总计(全部,46.1次,210分钟)233
这是我的代码:
flag = 1
for line in data:
if " innings " in line:
flag = 0
print('')
if line.startswith("Extras "):
flag = 1
print('')
if not flag and not " innings " in line:
print(line)
答案 0 :(得分:0)
您的计划必须在第一次出现Extras
时停止:
active = False # A variable `flag` is not very precisely named,
# better call it `active`, make it boolean
# and flip the values
for line in data:
if " innings " in line:
active = True # now we want to do things
print('')
continue # but not in this loop
if line.startswith("Extras "):
print('')
break # now we're done!
# alternative Method:
# active = False
if active:
print(line)
如果要存储所有事件:
active = False
stored = []
for line in data:
if " innings " in line:
tmp = []
active = True # now we want to do things
continue # but not in this loop
if line.startswith("Extras "):
stored.append(tmp)
active = False
continue
if active:
tmp.append(line)
您最终会得到一系列行列表以供进一步处理。