【发布时间】:2020-09-04 08:55:26
【问题描述】:
我正在尝试使用正则表达式从文本中提取数据。我想遍历正则表达式“选项”,然后将结果写入特定列表。
我认为我可能没有编写循环并正确引用列表。我在第 27 行收到一条错误消息:TypeError: list indices must be integers or slices, not re.Pattern。我曾尝试将正则表达式列表放入 range(),但随后出现此错误:TypeError: 'list' object cannot be interpreted as an integer 这次在第 18 行。我不确定如何解决这个问题?
请看下面我的代码:
import re
regexcode0 = re.compile(r'Test 0')
regexcode1 = re.compile(r'Test 1')
regexcode2 = re.compile(r'Test 2')
results_Test0 = []
results_Test1 = []
results_Test2 = []
allResults = [results_Test0, results_Test1, results_Test2]
regexlist = [regexcode0, regexcode1, regexcode2]
textBody = 'Hi there, Test 2 was a failure'
def text_extract(text):
for i in regexlist:
match = re.search(i, text)
if match:
matchObj = match.group()
allResults[i].append(matchObj)
if not match:
allResults[i].append('No Solution')
return allResults
print(text_extract(textBody))
我希望结果如下所示:
results_Test0 = ['No Solution']
results_Test1 = ['No Solution']
results_Test2 = ['Test 2']
【问题讨论】:
-
为什么要使用带有固定字符串的正则表达式?这些只是例子,对吧?顺便说一句,欢迎来到 SO!如果您需要建议,请查看How to Ask。
-
BTW 并行列表在我的经验中通常是不好的做法。您可能希望使用 dict 代替,可能使用 regex:result 对。
-
嗨 wjandrea - 是的,这些只是示例!感谢您编辑我的问题,这是我提出的第一个问题。还要感谢您对平行列表的建议。我会在以后合并它。
标签: python python-3.x list