Python和重新编译返回不一致的结果

2024-10-01 00:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将href="../directory"的所有实例替换为href="../directory/index.html"。在

在Python中,这个

reg = re.compile(r'<a href="../(.*?)">')
for match in re.findall(reg, input_html):
    output_html = input_html.replace(match, match+'index.html')

生成以下输出:

^{pr2}$

你知道为什么第二个链接可以用,但其他链接不行吗?在

来源相关部分:

<p> 

 <a href="../personal-autonomy/">autonomy: personal</a> |
 <a href="../principle-beneficence/">beneficence, principle of</a> |
 <a href="../decision-capacity/">decision-making capacity</a> |
 <a href="../legal-obligation/">legal obligation and authority</a> |
 <a href="../paternalism/">paternalism</a> |
 <a href="../identity-personal/">personal identity</a> |
 <a href="../identity-ethics/">personal identity: and ethics</a> |
 <a href="../respect/">respect</a> |
 <a href="../well-being/">well-being</a> 

</p> 

编辑:重复的'索引.html'实际上是多个匹配的结果。(例如,href=“../personal autonomy/index.htmlindex.htmlindex.htmlindex.html“是因为../个人自主性在原始资料中出现了四次)。在

作为一个通用的regex问题,如何在不添加额外的'索引.html“所有的比赛?在


Tags: reinputindex链接htmlmatchregdirectory
3条回答

我想我发现了问题

reg = re.compile(r'<a href="../(.*?)">')

for match in re.findall(reg, input_html):

output_html = input_html.replace(match, match+'index.html')

这里在for循环中修改“input_html”,然后再次搜索相同的“input_html”以查找正则表达式,这是错误:)

Don't parse html with regexs:

import re    
from lxml import html

def replace_link(link):
    if re.match(r"\.\./[^/]+/$", link):
        link += "index.html"
    return link

print html.rewrite_links(your_html_text, replace_link)

输出

^{pr2}$

你的平手是不是逃过了前两个.?在

reg = re.compile(r'<a[ ]href="[.][.]/(.*?)">')

但我会试着用lxml来代替。在

相关问题 更多 >