【问题标题】:Why do I keep getting this IndexError?为什么我不断收到此 IndexError?
【发布时间】:2017-07-24 09:34:36
【问题描述】:

我对 python 和一般编码是全新的。谁能理解我为什么会收到这个 IndexError?

Traceback (most recent call last):
  File "\\Mac\Home\Desktop\Python\Lab1\lab1_querystring.pageresults.addresssplit.headersadded.columnsadded.keysaddedtodictionary.py", line 54, in <module>
    city = splitaddress[1]
IndexError: list index out of range

我试图从中提取每个 if 语句/套件的列表有四个项目,但由于某种原因,它一直告诉我列表索引超出范围。

for listing in splititems:
    name = parse(listing,"itemprop=\"name\">","<").strip() # extract the business name

    # Try to extract the address into its constituent parts - street address, city, postal, see if you can put them into different columns in excel
    address = parse(listing,"<div class=\"ltext\" itemprop=\"address\" itemscope itemtype=\"http://schema.org/PostalAddress\">","</div>").strip() # extract the address
    splitaddress = address.split(',')

    streetaddress = splitaddress[0]
    city = splitaddress[1]
    postalcode = splitaddress[2]

    if len(splitaddress) >= 0:
            print splitaddress[0]

    if len(splitaddress) >= 1:
            print splitaddress[1]

    if len(splitaddress) >= 2:
            print splitaddress[2]

    phone = parse(listing,"itemprop=\"telephone\" content=\"","\"/>").strip() # extract the phone number

    print name, address, phone # take this out when you're finished your script - this is just for testing
    resultlist.append({'businessname':name,'streetaddress':streetaddress, 'city':city, 'postalcode':postalcode, 'phone':phone})
    del name,streetaddress,city,postalcode,phone

【问题讨论】:

  • 你应该多写代码。尝试参加在线课程或阅读一些有关 Python 的书籍。
  • 尝试移动各种if len(splitaddress) &gt;= 0你分配city之前。您会看到 splitaddress 不包含您认为的内容。
  • 看起来您的 parse 函数并没有按照您的想法执行...

标签: python python-2.7 index-error


【解决方案1】:

您的地址不包含逗号,而是另一个分隔符:

In [1]: address = "Mr. Foo; Spam street 42; Eggsville"

In [2]: address.split(',')
Out[2]: ['Mr. Foo; Spam street 42; Eggsville']

如果您要将其分配给splitaddress,则除splitaddress[0] 之外的所有内容都会引发IndexError

在继续之前检查len(splitaddress) &gt; 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2017-02-24
    • 2020-04-30
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多