python替换为捕获组

时间:2012-05-10 18:46:58

标签: python bash ubuntu batch-file

如何将“.nmv-fas”的所有实例更改为“title”标签之间的任何内容? 这有可能与python或有更好的方法吗?

基本上改变了:

<html>
<head>
<title>.rtpv05-tl</title>
</head>
<a href="http://www.youversion.com/bible/gen.1.nmv-fas">http://www.youversion.com/bible/gen.1.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.2.nmv-fas">http://www.youversion.com/bible/gen.2.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.3.nmv-fas">http://www.youversion.com/bible/gen.3.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.4.nmv-fas">http://www.youversion.com/bible/gen.4.nmv-fas</a>
<a href="http://www.youversion.com/bible/gen.5.nmv-fas">http://www.youversion.com/bible/gen.5.nmv-fas</a>

到这个

<html>
<head>
<title>.rtpv05-tl</title>
</head>
<a href="http://www.youversion.com/bible/gen.1.rtpv05-tl">http://www.youversion.com/bible/gen.1.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.2.rtpv05-tl">http://www.youversion.com/bible/gen.2.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.3.rtpv05-tl">http://www.youversion.com/bible/gen.3.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.4.rtpv05-tl">http://www.youversion.com/bible/gen.4.rtpv05-tl</a>
<a href="http://www.youversion.com/bible/gen.5.rtpv05-tl">http://www.youversion.com/bible/gen.5.rtpv05-tl</a>

2 个答案:

答案 0 :(得分:1)

awk -v text='.nmv-fas' '
    /<title>/ {title=$0; gsub(/<\/?title>/, "", title); replace=1}
    replace {gsub(text, title)}
    {print}
' file > file.tmp && mv file.tmp file

awk没有像sed的-i

这样的“就地”选项

当然,这取决于标题文本与<title>标记位于同一行。为安全起见,您应该使用HTML解析器来解析HTML。

答案 1 :(得分:0)

您可以使用正则表达式将标题拉出为字符串。假设你的html在某些字符串中:

import re
match = re.compile(r"<title>(.+)</title>",re.I|re.DOTALL)
title = match.group(1)

然后只需对字符串s

执行字符串替换
s.replace(".nmv-fas",title)
相关问题