gpt4 book ai didi

python - 正则表达式在两个标签之间查找单词

转载 作者:太空狗 更新时间:2023-10-30 00:29:52 25 4
gpt4 key购买 nike

如何在 python 中使用正则表达式来查找标签之间的单词?

s = """<person>John</person>went to<location>London</location>"""
......
.......
print 'person of name:' John
print 'location:' London

最佳答案

您可以使用 BeautifulSoup 进行此 HTML 解析。

input = """"<person>John</person>went to<location>London</location>"""
soup = BeautifulSoup(input)
print soup.findAll("person")[0].renderContents()
print soup.findAll("location")[0].renderContents()

另外,在 python 中使用 str 作为变量名并不是一个好习惯,因为 str() 在 python 中意味着不同的东西。

顺便说一句,正则表达式可以是:

import re
print re.findall("<person>(.*?)</person>", input, re.DOTALL)
print re.findall("<location>(.*?)</location>", input, re.DOTALL)

关于python - 正则表达式在两个标签之间查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22247957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com