我这个程序中有三个列表。'library'包含了大量的文本,'references'包含了references中互相跟随的单词列表,而'possibles'则是查看'references'中每项一起出现的时间,这样它就可以得到下面的单词。
程序得到了'references'的长度,所以它知道要检查'库'中的多少个项目,但是检查references中是否有2个项目的那段代码返回了'意外的缩进',我不明白为什么。即使我删除缩进项,它也会返回错误。如果它没有缩进,就会出现错误,因为它破坏了代码的其他部分。
下面是整个函数。除了缩进错误之外,整个程序都能正常工作。
def possibles_compile():
compile = 'yes'
global temp_possibles
temp_possibles = []
while compile != 'no':
if len(reference) == 1:
for i in range(library_length):
try:
if library[i] == reference[0]:
try:
temp_possibles.append(library[i + 1])
except IndexError:
temp_possibles.append(library[0])
elif len(reference) == 2:
for i in range(library_length):
if library[i] == reference[0]:
try:
if library[i + 1] == reference[1]:
try:
temp_possibles.append(library[i + 2])
except IndexError:
temp_possibles.append(library[0])
except IndexError:
if library[0] == reference[1]:
temp_possibles.append(library[1])
elif len(reference) == 3:
for i in range(library_length):
if library[i] == reference[0]:
try:
library[i + 1] == reference[1]:
except IndexError:
if library[0] == reference[1]:
if library[1] == reference[2]:
temp_possibles.append(library[2])
else:
try:
if library[i + 2] == reference[2]:
try:
temp_possibles.append(library[i + 3])
except IndexError:
temp_possibles.append(library[0])
except IndexError:
if library[0] == reference[2]:
temp_possibles.append(library[1])
elif len(reference) == 4:
for i in range(library_length):
if library[i] == reference[0]:
try:
library [i + 1] == reference[1]:
except IndexError:
if library[0] == reference[1]:
if library[1] == reference[2]:
if library[2] == reference[3]:
temp_possibles.append(library[3])
else:
try:
library[i + 2] == reference[2]:
except IndexError:
if library[0] == reference[2]:
if library[1] == reference[3]:
temp_possibles.append(library[2])
else:
try:
if library[i + 3] == reference[3]:
try:
temp_possibles.append(library[i + 4])
except IndexError:
temp_possibles.append(library[0])
except IndexError:
if library[0] == reference[3]:
temp_possibles.append(library[1])
compile = 'no'
return 'done'
的评论让我大开眼界,我有一个。try
没有 except
和大量错位的冒号。去掉冒号和 try
无懈可击
行之前。
if library[i] == reference[0]:
你创建了一个异常处理程序,但只把try子句和每一个... 尝试 必须有一个相关的 除了 到它。所以我建议你把你的代码改成。
try:
if library[i] == reference[0]:
try:
temp_possibles.append(library[i + 1])
except IndexError:
temp_possibles.append(library[0])
except Exception:
pass # put the exception code you want to executed when handling this exception here
或者,如果没有必要的话,你也可以去掉那个try子句。
另外,要注意以下几行。
library[i + 1] == reference[1]:
library [i + 1] == reference[1]:
library [i + 1] == reference[1]:
你在不该用冒号的地方用了冒号 (除非你想创建一个条件或一个迭代子句) 。