首页 > 解决方案 > 列表和整数上的子字符串解析

问题描述

更新:如果 sec_good 为空解决了问题,则向 sec_good 添加一个“0”。

我正在解析非结构化 pdf 并返回一些选择变量。当我检查特定模式的列表时遇到了一个小问题,因为每个列表都不相同。

95% 的列表包含我在 sec_good[0][1] 中寻找的内容,但如果那里没有任何内容,则循环显然会中断并引发索引错误。有没有办法检查 sec_good[0] 是否存在而不中断?

例如:

secs = re.finadall(regex,lines)
sec_re = r"(Find the pair I'm looking for and replace the divider with --)"       
for o in secs:
    for p in o:
       if len(p) != 0:
           p = re.sub(sec_re,"--",p)
               p = p.split("--")
               print("p is %s" % p)
               print("len p is %s" % len(p))
               sec_good.append(p)
if len(sec_good) == 0: ###This works.
    sec_good.append("0") ##
if len(sec_good) >= 1:
    Section.append(sec_good[0][0])
else:
    Section.append("0")
if len(sec_good[0]) >= 2: #This is what breaks.
    Sec2.append(sec_good[0][1])
else:
    Sec2.append("0")

我尝试了一些东西,包括。

def checker(lst):
    if len(lst[0][1]) > 0:
    return True
else:
    return False

关于我忽略的任何想法?sec_good如果找到“--” ,我将第二个值附加到 Sec2 中。如果什么都没有,我会尝试附加“0”。

如果 len(sec_good[0]) >= 2 中的文件“C:/Users/itsme/parser.py”,第 105 行:

IndexError:列表索引超出范围

标签: python-3.x

解决方案


推荐阅读