我需要帮助来理解此代码。我无法理解循环。有人可以分解并解释吗? “ 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 :(得分:2)
您好,尝试尽可能地回答: 说的很简单: While循环0检查行尾 While循环1检查标记(或行)的结尾 While循环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] 如果是这样,它将i加1并运行另一个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
然后它会中断外部 while循环0 。
break
对于反馈和我的答案得到改善感到高兴。干杯
答案 1 :(得分:1)
我可以解释一下。
I = 0
这将创建一个名为I的新变量,并将其设置为零。
while I < Len (line)
这一切意味着,在此循环中执行的所有代码将继续执行,直到我大于行数为止。如您所见,在循环中,它将i加1。这意味着直到循环结束还需要几秒钟。
答案 2 :(得分:1)
我在代码中添加了一些注释,希望可以使其更易于理解。 添加针对丢失或无效数据的错误处理时,应查找可能需要一些不可用数据的地方。
如果data = ur.urlopen(link)
不返回任何数据怎么办? urlopen
可以抛出任何异常吗?您可以在documentation中找到此信息。
一旦您知道可能的异常,就可以使用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.