【问题标题】:TypeError: list indices must be integers or slices, not re.PatternTypeError:列表索引必须是整数或切片,而不是 re.Pattern
【发布时间】: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


【解决方案1】:

results_Testn 的类型是listlist[index] 的语法需要一个整数来指示列表中的特定位置。您正在尝试使用 i 作为索引,并且它的类型不是整数,因此会导致错误。如果您希望 for 循环的每次迭代都使用整数,可以使用 enumerate 函数:

for index, i in enumerate(regexlist):
   #do something 

在本例中,i 表示 re 模式,index 是表示其在列表中的位置的数字,因此您可以使用allresults[index] 保存结果。

【讨论】:

  • 感谢您的帮助!我会努力解决的!
猜你喜欢
  • 2016-09-16
  • 1970-01-01
  • 2019-07-04
  • 2015-12-09
  • 2021-11-28
  • 2020-09-23
  • 2019-10-01
相关资源
最近更新 更多