Python循环if语句退出



我想在pdf文件的第一页中找到两个元素。以P开头的元素和以N开头的元素。即使已经找到一个元素,仍然需要继续搜索另一个元素。

如果找到p,继续搜索N如果找到N,则继续搜索P当找到P和N时,停止搜索

我的循环有问题,只有在没有p的情况下才能找到N。我知道if语句有问题,但我似乎无法纠正。

if text is not None:
p_new = "NoPFound"
n_new = "NoNFound"
for line in text.split('n'):
#get p
if line.startswith('P '):
pieces = line.split()
p_old = pieces[1]
p_new = (p_old[7:11]) + (p_old[0:6])
break
#get n
if line.startswith('N '):
pieces = line.split()
n_old = pieces[1]                        
n_new = (n_old[0:15]) + "/" + (n_old[18:20])
break
list_parsed_items.append([p_new, n_new])

使用标志。你有一个小型的状态机。

if text is not None:
p_new = None
n_new = None
for line in text.splitlines():
#get p
if not p_new and line.startswith('P '):
pieces = line.split()
p_old = pieces[1]
p_new = (p_old[7:11]) + (p_old[0:6])
#get n
if not n_new and line.startswith('N '):
pieces = line.split()
n_old = pieces[1]                        
n_new = (n_old[0:15]) + "/" + (n_old[18:20])
if p_new and n_new:
break
list_parsed_items.append([p_new, n_new])

最新更新