【问题标题】:list indices must be integers, not str - regular expression列表索引必须是整数,而不是 str - 正则表达式
【发布时间】:2015-01-26 05:09:07
【问题描述】:

我正在尝试在以“.torrent”一词结尾的列表中查找所有数据。为此,我使用了正则表达式。当我写这篇文章时:

for k in link_torrent2:
m=re.findall(r'\S+\.torrent',link_torrent2[k])
if m:
    link2.append(m)

我遇到了一个错误:

list indices must be integers, not str 

所有代码:

import re
link2=[]

link_torrent1=[u'#', u'/torrent_download/3797378/THE+BLACKLIST+%282014%29+S02E02+x264+1080p%28WEB-DL%29+eng+NLsubs+TBS.torrent',
    u'/category/581/', u'/torrent/3797378/THE+BLACKLIST+%282014%29+S02E02+x264+1080p%28WEB-DL%29+eng+NLsubs+TBS.html',
    u'/torrent_download/3795431/The+Blacklist+S02E02+720p+HDTV+x264+AAC+-+Ozlem.torrent', u'/category/581/',
    u'/torrent/3795431/The+Blacklist+S02E02+720p+HDTV+x264+AAC+-+Ozlem.html', u'/torrent_download/3795314/The.Blacklist.S02E02.HDTV.x264-ChameE.torrent']
link_torrent2=[str(x) for x in link_torrent1]

print link_torrent1

for k in link_torrent2:
    m=re.findall(r'\S+\.torrent',link_torrent2[k])  ##here shows error
    if m:
        link2.append(m)
print m

【问题讨论】:

  • 声明必须是m=re.findall(r'\S+\.torrent',k)
  • 那是因为你使用了迭代器。

标签: python regex list


【解决方案1】:

k 不是整数。它是link_torrent2 列表中的一个元素。直接使用即可:

for k in link_torrent2:
    m=re.findall(r'\S+\.torrent', k)

那是因为 Python for 循环实际上是 Foreach loops;每次迭代都会将输入可迭代 (link_torrent2) 中的下一个元素分配给您选择的目标,在本例中为 k

您可以使用str.endswith() method:而不是使用正则表达式:

for k in link_torrent2:
    if k.endswith('.torrent'):
        link2.append(m)

或者,使用list comprehension 更紧凑:

link2 = [k for k in link_torrent2 if k.endswidth('.torrent')]

【讨论】:

    【解决方案2】:

    您不需要re.findall 函数,只需re.search 就可以了。

    >>> link_torrent2=[str(x) for x in link_torrent1]
    >>> [i for i in link_torrent2 if re.search(r'.*\.torrent$', i)]
    ['/torrent_download/3797378/THE+BLACKLIST+%282014%29+S02E02+x264+1080p%28WEB-DL%29+eng+NLsubs+TBS.torrent', '/torrent_download/3795431/The+Blacklist+S02E02+720p+HDTV+x264+AAC+-+Ozlem.torrent', '/torrent_download/3795314/The.Blacklist.S02E02.HDTV.x264-ChameE.torrent']
    

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2016-02-09
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 2016-07-20
      相关资源
      最近更新 更多