python-3.x - 列表和整数上的子字符串解析
问题描述
更新:如果 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:列表索引超出范围
解决方案
推荐阅读
- matlab - 此代码如何用于绘制有障碍物的网格?
- javascript - 当我在 HTML 文本框中输入内容时如何突出显示结果集中的匹配文本
- memory-management - final 是否必须是编译器中的元素或错误
- shell - Ripgrep 仅排除文件夹根目录中的文件
- java - 如何使用java读取.log文件?
- mysql - 如何只更新那些可整除的 MySQL
- php - 如何使用 ffmpeg 功能按比例(纵横比)图像?
- excel - Excel:如果一个单元格包含两个单词,我将如何使用第一个单词的第一个字母和第二个单词的前两个字母?
- recursion - 深度优先搜索在返回时不会创建新对象
- c# - 无法在启动类中注入 IAntiforgery