我需要帮助理解这段代码。我听不懂这些循环。有人能把它分解并解释一下吗?"i=0"在本程序中代表什么。我还必须添加对丢失和无效数据的错误处理。我将不胜感激。非常感谢。
i = 0
while i < len(line):
if line[i] == '<':
i = i + 1
while i < len(line) and line[i] != '>':
tag += line[i]
i = i + 1
if tag not in fields:
break;
i = i + 1;
while i < len(line) and line[i] != '<':
value += line[i]
i = i + 1
break;
嗨,尽可能地回答:非常简单:而循环0检查行的末尾循环1检查标记(或行(的末尾当循环2检查值(或行(的末尾时
更详细:
i = 0
[WHILE LOOP 0]i=0是行的开始,WHILE循环直到i达到行的长度,以检查行是否仍有内容。
while i < len(line):
if子句检查是否打开html标记。
if line[i] == '<':
i = i + 1
[WHILE LOOP 1]如果是,它会将1添加到i,并运行另一个WHILE循环,直到标记关闭(>(或到达行的末尾。
while i < len(line) and line[i] != '>':
tag += line[i]
i = i + 1
如果标记不在上面的字段列表中,则会中断While Loop 0
if tag not in fields:
break;
当while循环成功并且标记结束时,会添加该+1,以转到行中的下一个字符
i = i + 1
[WHILE LOOP 2]然后它转到下一个字符,并假设将出现值。while循环循环,直到它再次找到一个html标记开始。'<'或者这条线在尽头。
while i < len(line) and line[i] != '<':
value += line[i]
i = i + 1
然后,当循环0时,它会破坏外部。
break
对我的回答的反馈和改进感到高兴。干杯
我可以对此进行一点解释。
I = 0
这就是创建一个名为I的新变量,并将其设置为零。
while I < Len (line)
所有这些都意味着,在这个循环中执行的任何代码都将继续执行,直到I大于有多少行。正如你所看到的,在循环中,它将i加1。这意味着需要几秒钟才能结束循环。
我在代码中添加了一些注释,希望这些注释能更容易理解。当为丢失或无效的数据添加错误处理时,您应该查找可能需要一些不可用数据的地方。
如果data = ur.urlopen(link)
不返回任何数据,会发生什么情况?urlopen
可以抛出任何异常吗?您可以在文档中找到这些信息。
一旦您了解了可能的异常,就可以使用try/except
块来捕捉它们。例如:
try:
raise ValueError # Exception happens here.
except ValueError: # You catch it here.
print("Cought a Value Error.") # And handle it here.
i = 0 # This seems to be a index for each character in a line. 0 is the first character in the line.
while i < len(line): # Loop until the index reaches the last character in the line.
# If you find the < character at position i.
if line[i] == '<':
i = i + 1
while i < len(line) and line[i] != '>': # Loop until you find the matching >.
tag += line[i] # Save all character in between < and >
i = i + 1
if tag not in fields: # Didn't find what you where looking for so exit the while loop.
break;
i = i + 1;
# You are still in the line but the current character is not <.
while i < len(line) and line[i] != '<':
# Save all characters until the line ends or you find a <.
value += line[i]
i = i + 1
break; # Exit the while loop.