摘自文档,以下是显示正则表达式方法 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])