10

摘自文档,以下是显示正则表达式方法 findall 如何工作的片段,并确认它确实返回了一个列表。

re.findall(r"\w+ly", text)
['carefully', 'quickly']

IndexError: list index out of range但是,以下代码片段在尝试访问 findall 返回的列表的第零个元素时会生成越界错误 ( )。

相关代码片段:

population = re.findall(",([0-9]*),",line)
x = population[0]
thelist.append([city,x])

为什么会这样?

对于更多背景知识,以下是该片段如何适合我的整个脚本:

import re

thelist = list()
with open('Raw.txt','r') as f:
    for line in f:
        if line[1].isdigit():
            city = re.findall("\"(.*?)\s*\(",line)
            population = re.findall(",([0-9]*),",line)
            x = population[0]
            thelist.append([city,x])

with open('Sorted.txt','w') as g:
    for item in thelist:
        string = item[0], ', '.join(map(str, item[1:]))
        print string

编辑:阅读下面的评论,了解为什么会发生这种情况的一些背景。我的快速修复是:

if population: 
        x = population[0]
        thelist.append([city,x])
4

3 回答 3

12

re.findall如果没有匹配项,将返回一个空列表:

>>> re.findall(r'\w+ly', 'this does not work')
[]
于 2013-02-21T00:55:24.330 回答
3

re.findall在没有匹配的情况下可以返回一个空列表。如果您尝试访问[][0],您将看到IndexError.

考虑到没有匹配,您应该使用以下内容:

match = re.findall(...)
if match:
  # potato potato
于 2013-02-21T00:58:34.467 回答
1

我有同样的问题。解决方案似乎很简单,我不知道为什么我没有考虑它。

if match:

代替

if match[0]:
于 2015-11-17T15:30:22.750 回答