Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 代码挂起,无限循环?_Python - Fatal编程技术网

Python 代码挂起,无限循环?

Python 代码挂起,无限循环?,python,Python,我正在尝试编写一些python代码来提取数据。这几乎是正确的,但它似乎挂在制作第一个文件的末尾。某处有无限循环吗 train = open('mp_crf_train.txt', 'r') lines = train.readlines() number = 0 for i in lines: filename = str(number) + ".txt" outfile = open(filename,"w") lst = i.split(' ') x=1

我正在尝试编写一些python代码来提取数据。这几乎是正确的,但它似乎挂在制作第一个文件的末尾。某处有无限循环吗

train = open('mp_crf_train.txt', 'r')
lines = train.readlines()
number = 0

for i in lines:
    filename = str(number) + ".txt"
    outfile = open(filename,"w")
    lst = i.split(' ')
    x=1
    #while x < len(lst):
    for word in lst:
        if '<' in word and '/' not in word:
            sword = word[1:len(word)-1]
            close = '</'+ sword + '>'
            while lst[x] != close:
                    outfile.write(lst[x])
                    outfile.write('  ')
                    outfile.write(sword)
                    outfile.write('\n')
                    if x!=len(lst)-1:
                       x=x+1
            x=x+1
    number = number+1   
train=open('mp\u crf\u train.txt','r')
lines=train.readlines()
数字=0
对于行中的i:
filename=str(number)+“.txt”
outfile=open(文件名“w”)
lst=i.split(“”)
x=1
#当x如果是的话。你怎么知道这个循环

        while lst[x] != close:

会结束吗?
列表中是否必须关闭
?那么空格呢(我想这是HTML或者一些不知道空格的东西)?假设右大括号的形式正好是
'

这里是唯一可以成为无限循环的地方:

while lst[x] != close:

如果
lst[x]
从未
关闭
,则将是infinte。每次迭代时都要打印一个
print(lst[x])
(或者只检查
outfile
)中的相关行,并将其与您期望的内容进行比较——您可能遗漏了一个微不足道的差异。

这是一个无限循环的组成部分。如果您到达
lst
的末尾,但没有找到
close
,那么您将处于一个无限循环中,因为您要防止x递增。如果你得到了一个索引错误(很可能)-你根据长度检查x的修正是导致无限循环的原因

        while lst[x] != close:
                ...
                if x!=len(lst)-1:
                   x=x+1
您可能应该使用的是

        while x<len(lst) and lst[x] != close:
                ...
                x=x+1
如果您需要跟踪
x

        for item in lst:
            if item == close:
                break
            ... 
        for x, item in enumerate(lst):
            if item == close:
                break
            ... 

如果
循环从未找到
close
?如果有嵌套的标记会发生什么?您不必问我们是否有无限循环。打印一些调试语句,您就会发现。我建议您也学习如何进行一般性的调试。不过应该是这样!close应该与列表中的最后一个成员完全相同。列表[x]是否永远找不到结尾?@KEYSER还挂起了我的调试器…HTML不是一种常规语言,因此建议OP尝试使用正则表达式来解析它是很残忍的。谢谢!使用您的第一个建议。@user2951046如果gnibbler的答案对您有用,请将答案标记为已接受。