Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.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 是否将超链接中的href值替换为Windows文件路径?_Python_Regex_Python 3.x - Fatal编程技术网

Python 是否将超链接中的href值替换为Windows文件路径?

Python 是否将超链接中的href值替换为Windows文件路径?,python,regex,python-3.x,Python,Regex,Python 3.x,我试图使用Python中的sub方法和正则表达式来搜索的所有实例并替换为Windows文件路径:,但它在倒数第二行(regex_replace=…)上一直失败。这是我的密码: matches = re.search(r'<xref(\s*)href="(\d+)">', html) if matches: topicid = matches.group(2) windowsfilepath = '3.1 First Level\3.1.1 Second Level\3

我试图使用Python中的sub方法和正则表达式来搜索
的所有实例并替换为Windows文件路径:
,但它在倒数第二行(regex_replace=…)上一直失败。这是我的密码:

matches = re.search(r'<xref(\s*)href="(\d+)">', html)
if matches:
    topicid = matches.group(2)
    windowsfilepath = '3.1 First Level\3.1.1 Second Level\3.1.1.2 Third Level.txt'
    regex_search = r'<xref(\s*)href="' + re.escape(topicid) + r'">'
    regex_replace = r'<xref href="'+ re.escape(windowsfilepath) + r'">'
    html = re.sub(regex_search,regex_replace,html)
matches=re.search(r'',html)
如果匹配:
topicid=匹配项。组(2)
windowsfilepath='3.1第一级\3.1.1第二级\3.1.1.2第三级.txt'
regex_search=r“”
regex_replace=r''
html=re.sub(正则表达式搜索、正则表达式替换、html)

我很确定这与转义
windowsfilepath
中的反斜杠和/或句点有关,但我尝试过使用re.escape(),文本永远不会被替换。

如果您将
windowsfilepath
放在额外的双引号中,您应该能够简单地用
re.sub()
替换所有匹配项,如下所示:

windowsfilepath = '"3.1 First Level\3.1.1 Second Level\3.1.1.2 Third Level.txt"'
new_html = re.sub(r'(?<=\<xref href\=)("\d+")', windowsfilepath, html)

为什么是a-1,我的问题中有什么不清楚的地方吗?我尝试了你的解决方案,但现在链接看起来是这样的:ETX字符在升华文本中以粗体显示,不确定它代表什么。
windowsfilepath = '"3.1 First Level/3.1.1 Second Level/3.1.1.2 Third Level.txt"'
new_html = re.sub(r'(?<=\<xref href\=)("\d+")', windowsfilepath, html)