Python 如何获取文本并替换某些标记之间的文本

Python 如何获取文本并替换某些标记之间的文本,python,html,regex,html-parsing,Python,Html,Regex,Html Parsing,给定一个字符串 "<p> >this line starts with an arrow <br /> this line does not </p>" “>此行以箭头开头此行不以箭头开头 或 “>此行以箭头开头此行不” 如何找到以箭头开头并用div环绕的线 使其成为: "<p> <div> >this line starts with an arrow </div> <br /> this l

给定一个字符串

"<p> >this line starts with an arrow <br /> this line does not </p>"
“>此行以箭头开头
此行不以箭头开头

“>此行以箭头开头

此行不

如何找到以箭头开头并用div环绕的线

使其成为:

"<p> <div> >this line starts with an arrow </div> <br /> this line does not </p>
“>此行以箭头开头
此行不以箭头开头


您可以尝试使用
\s+(>.*)pand用codediv matched_group/div/code替换匹配的组。在这里模式查找包含在code>
中的任何内容,您可以尝试使用
\s+(>.*)pand用codediv matched_group/div/code替换匹配的组。在这里模式查找包含在code>
中的任何内容。您可以尝试此正则表达式

>(\w[^<]*)
>(\w[^>>导入re
>>>str='“>此行以箭头开头
此行不以箭头开头”
>>>m=re.sub(r'>(\w[^你可以试试这个正则表达式

>(\w[^<]*)
>(\w[^>>导入re
>>>str='“>此行以箭头开头
此行不以箭头开头”
>>>m=re.sub(r'>(\w[^因为您正在解析的是HTML,所以请使用该工具进行此项工作-HTML解析器,如

用于查找以
开头的所有文本节点,并使用新的
div
标记:

from bs4 import BeautifulSoup

data = "<p> >this line starts with an arrow <br /> this line does not </p>"

soup = BeautifulSoup(data)
for item in soup.find_all(text=lambda x: x.strip().startswith('>')):
    item.wrap(soup.new_tag('div'))

print soup.prettify()
从bs4导入美化组
data=“>此行以箭头开头
此行不以箭头开头 汤=美汤(数据) 对于汤中的项目。查找所有(text=lambda x:x.strip().startswith('>'): 项目.包装(汤.新标签('div')) 打印汤。美化
印刷品:

<p>
    <div>
    >this line starts with an arrow
    </div>
    <br/>
    this line does not
</p>

>这一行以箭头开头

这条线不行


由于您正在解析的是HTML,因此请使用该工具—HTML解析器,如

用于查找以
开头的所有文本节点,并使用新的
div
标记:

from bs4 import BeautifulSoup

data = "<p> >this line starts with an arrow <br /> this line does not </p>"

soup = BeautifulSoup(data)
for item in soup.find_all(text=lambda x: x.strip().startswith('>')):
    item.wrap(soup.new_tag('div'))

print soup.prettify()
从bs4导入美化组
data=“>此行以箭头开头
此行不以箭头开头 汤=美汤(数据) 对于汤中的项目。查找所有(text=lambda x:x.strip().startswith('>'): 项目.包装(汤.新标签('div')) 打印汤。美化
印刷品:

<p>
    <div>
    >this line starts with an arrow
    </div>
    <br/>
    this line does not
</p>

>这一行以箭头开头

这条线不行


你是如何定义“行”的?请用答案回答,因为……你是如何定义“行”的“?选择答案,因为,嗯…+1。当我点击这个问题时,我真的很担心会有关于正则表达式的东西…+1。当我点击这个问题时,我真的很担心会有关于正则表达式的东西。。。