如何在python中使用正则表达式来查找标签之间的单词?
s = """<person>John</person>went to<location>London</location>"""
......
.......
print 'person of name:' John
print 'location:' London
Run Code Online (Sandbox Code Playgroud)
您可以使用BeautifulSoup此html解析.
input = """"<person>John</person>went to<location>London</london>"""
soup = BeautifulSoup(input)
print soup.findAll("person")[0].renderContents()
print soup.findAll("location")[0].renderContents()
Run Code Online (Sandbox Code Playgroud)
此外,str在python中使用变量名称不是一个好习惯,因为它在python中str()意味着不同的东西.
顺便说一句,正则表达式可以是:
import re
print re.findall("<person>(.*?)</person>", input)
print re.findall("<location>(.*?)</location>", input)
Run Code Online (Sandbox Code Playgroud)
import re
pattern = r"<person>(.*?)</person>"
re.findall(pattern, str, flags=0) #you may need to add flags= re.DOTALL if your str is multiline
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
12147 次 |
| 最近记录: |