我必须从网站中提取两列。我知道如何读取行并打印它们但我只提取第一列和第三列时遇到问题,每次我尝试将变量附加到行并尝试打印变量时它会给我一个错误但是如果我使用print (行[2])它可以工作,但最后它会说索引超出范围。我不明白为什么?这是我做的:
import urllib.request
import csv
with urllib.request.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data") as webpage:
reader = csv.reader(webpage.read().decode('utf-8').splitlines())
for row in reader:
cor = row[0]
cors = row[2]
print(cors)
答案 0 :(得分:3)
在数据集的最后,有一个空行,它被存储为空列表。
您可以使用以下条件检查:
import urllib.request
import csv
with urllib.request.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data") as webpage:
reader = csv.reader(webpage.read().decode('utf-8').splitlines())
for row in reader:
if not row:
continue
cor = row[0]
cors = row[2]
print(cors)
答案 1 :(得分:3)
我的尝试
import urllib
import csv
webpage =urllib.urlopen("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")
reader = csv.reader(webpage.read().decode('utf-8').splitlines())
for row in reader:
if row:
cor = row[0]
cors = row[2]
print cor,cors