我逐行浏览了此代码,并解释了每个步骤。但是,由于我对python非常陌生(例如这是我的第一个工作),因此对于该函数的功能/为什么收到错误消息感到非常困惑。任何帮助,将不胜感激!

print("Exercise 2 begins")
import csv
c = 0
t = 0

with open('adele.csv','r') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t')
for line in csvdata:
    t = t + 1
    try:
        if 'grammy' in line[5]:
            c = c + 1
            print(c + ": " + t + ": " + str(line[5]))   # (7) Describe the purpose of this line
    except IndexError:
        pass

csvfile.close()
print("Exercise 2 ends\n")

最佳答案

错误消息是该代码应在for line in csvdata:之后缩进。

print("Exercise 2 begins")

import csv  # Include csv package to allow processing of csv files
c = 0       # Initialize a variable "c" with value "0"
t = 0       # Initialize a variable "t" with value "0"

# (1)  You will run into an error when running this code.
#      What is the error message?
#      What does the message mean and how do you fix it?

with open('adele.csv','rb') as csvfile:
    csvdata = csv.reader(csvfile, delimiter='\t') # (2) What does this line mean
    for line in csvdata:                          # (3) What does this line mean
        t = t + 1         # (4) Describe the purpose of this line
        try:
            if 'grammy' in line[5]:  # (5) What does this line mean and
                                     # what is in line[5]
                c = c + 1            # (6) What does this line mean
                print(c + ": " + t + ": " + str(line[5])) # (7) What does this line mean
        except IndexError:
            pass

根据adele.csv的不同,此代码可能有效也可能无效。试试看,并尝试了解它的作用和方式。没有错误消息,将更易于理解。

该代码可能会检查Adele赢得的格莱美奖的数量,但是如果没有看到adele.csv很难说。

10-08 07:57