Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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中嵌套While和For循环不停止_Python_Python 2.7_For Loop_While Loop - Fatal编程技术网

在python中嵌套While和For循环不停止

在python中嵌套While和For循环不停止,python,python-2.7,for-loop,while-loop,Python,Python 2.7,For Loop,While Loop,我正在使用Python 2.7程序将标记(.md)文件转换为HTML。然而,有一个例子,while循环没有正确退出,只是一次又一次地循环相同的数字 def链接(行): 链接列表=[] 链接字符串=“” 计数=0 左括号=0 右括号=0 左父H=0 右父H=0 对于行中的字符: 链接列表。附加(字符) 当计数

我正在使用Python 2.7程序将标记(.md)文件转换为HTML。然而,有一个例子,while循环没有正确退出,只是一次又一次地循环相同的数字

def链接(行):
链接列表=[]
链接字符串=“”
计数=0
左括号=0
右括号=0
左父H=0
右父H=0
对于行中的字符:
链接列表。附加(字符)
当计数<(len(链接列表)):
如果链接列表[计数]=“[”:
左括号=计数
对于链接列表中的x[左括号+1:]:
如果x==“]”:
右括号=链接列表索引(x)
如果x==“(”:
left\u parenth=链接列表索引(x)
如果x==”):
right\u parenth=link\u list.index(x)
打破
列表=链接列表[左括号+1:右括号]
str1=''.join(一个列表)
href\u list=link\u list[左家长+1:右家长]
str2=''.join(href_列表)
链接字符串=链接字符串+“”
计数=右\u父项H+1
如果链接列表[计数]!="[":
链接字符串=链接字符串+链接列表[计数]
计数+=1
打印链接字符串
链接(“lorem ipsum[内括号](URL链接),[内括号2](URL2)”)
此处:

            if x == "]":
                right_bracket = link_list.index(x)
            if x == "(":
                left_parenth = link_list.index(x)
            if x == ")":
                right_parenth = link_list.index(x)
                break

您使用括号/父项作为索引,因此应该直接将x传递给它们。通过使用link_list.index(x),它总是返回从左侧找到的第一个字符,这就是循环被卡住的原因。

或者,您可以使用regex。这将大大减少代码

import re
def link(line):
    return re.sub(r'\[(.*?)\]\((.*?)\)', r'<a href="\2">\1</a>', line)

link("The biggest headliners usually perform at the Orpheum Theatre, the [Overture Center](https://en.wikipedia.org/wiki/Overture_Center), [Breese Stevens Field](https://en.wikipedia.org/wiki/Breese_Stevens_Field), the [Alliant Energy Center](https://en.wikipedia.org/wiki/Alliant_Energy_Center), or the UW Theatre on campus.")
重新导入
def链路(线路):
返回re.sub(r'\[(.*?\]\(.*?)',r'',第行)
林克(“最大的头条人物通常在[序曲中心]俄耳甫姆剧院演出(https://en.wikipedia.org/wiki/Overture_Center),[Breese Stevens Field](https://en.wikipedia.org/wiki/Breese_Stevens_Field),即[Alliant能源中心](https://en.wikipedia.org/wiki/Alliant_Energy_Center),或校园内的UW剧院。”)
输出:

The biggest headliners usually perform at the Orpheum Theatre, the <a href="https://en.wikipedia.org/wiki/Overture_Center">Overture Center</a>, <a href="https://en.wikipedia.org/wiki/Breese_Stevens_Field">Breese Stevens Field</a>, the <a href="https://en.wikipedia.org/wiki/Alliant_Energy_Center">Alliant Energy Center</a>, or the UW Theatre on campus.
最大的头条人物通常在俄耳甫姆剧院、学校、学校或华盛顿大学剧院演出。
继续并在Regex101上试用:


我无法使用单个字符串获得结果,脚本似乎卡在了第行
link\u string=link\u string+''