python - 在迭代列表时,将值和接下来的 2 个值添加到新列表中
问题描述
我目前正在制作一个程序来扫描 PDF 文件并查找关键字“Ref”。一旦找到这个词,我需要获取接下来的两个字符串,“code”和“shares”,并将它们添加到一个新列表中,以便稍后导入 Excel。
我编写了代码以从 PDF 文件中获取文本并将其添加到列表中。然后,我遍历此列表并查找“Ref”关键字。当找到第一个时,它将它添加到列表中没有问题。但是,当涉及到下一个时,它将 Ref 的第一个实例(+代码和共享)再次添加到列表中,而不是 PDF 文件中的下一个...
这是将 Ref + code + share 添加到新列表(python 3)的代码:
for word in wordList:
match = 'false'
if word == 'Ref':
match = 'true'
ref = word
code = wordList[wordList.index(ref)+1]
shares = wordList[wordList.index(ref)+2]
if match == 'true':
refList.append(ref)
refList.append(code)
refList.append(shares)
这是输出:
['Ref','1','266','Ref','1','266','Ref','1','266','Ref','1','266','参考','1','266','参考','1','266']
正如您所看到的,它每次都具有相同的参考编号......正确的输出应该是这样的:
['Ref','1','266','Ref','2','642','Ref','3','435','Ref','4','6763']等...
如果有人知道为什么它总是在 wordList 中的每个“Ref”实例中添加第一个 ref 和代码,请告诉我!我很卡住!谢谢
解决方案
您的问题是,对 wordlist 的 index 方法的调用只会返回您可以处理的第一个实例。IE 你总是会得到“Ref”的第一个实例。相反,更好的方法是在列表上使用枚举,这将在您进行时为每个条目提供索引和值,然后您可以只引用索引值来获取接下来的两个元素。下面是代码示例。
data = """
this
Ref
1
266
that
hello
Ref
2
642"""
refList = []
wordList = [item.rstrip() for item in data.splitlines()]
for index, word in enumerate(wordList):
match = 'false'
if word == 'Ref':
match = 'true'
ref = word
code = wordList[index+1]
shares = wordList[index+2]
if match == 'true':
refList.append(ref)
refList.append(code)
refList.append(shares)
print(refList)
输出
['Ref', '1', '266', 'Ref', '2', '642']
您还可以清理并删除许多不需要的代码,然后将其编写为:
for index, word in enumerate(wordList):
if word == 'Ref':
refList += [word, wordList[index+1], wordList[index+2]]
推荐阅读
- powershell - 如何将一个脚本的 1 个输出存储到另一个脚本?
- java - Azure 容器实例 (Windows) 是否支持访问表存储
- python - 元素不可交互的硒
- c# - C# 进程在 Process.Start() 之后被取消
- python - 有没有一种方法可以绘制 CSV 文件中的数据,其中每列中的每 10 个数据点是同一图表中的不同线?
- android - 为什么我的自定义视图 RecyclerView 项目“不可见”
- excel - 为什么它没有将任何值转移到另一张纸上?
- python-3.x - 如何在python中为子类中的父类设置属性?
- javascript - 创建 HTML 和 JS 小部件并将它们集成到本机和混合应用程序
- python - Pandas - 有条件地连接两列