gpt4 book ai didi

python - 找到一个xml标签并将标签名称替换为python

转载 作者:行者123 更新时间:2023-12-01 05:13:13 25 4
gpt4 key购买 nike

我正在解析的kml文件: http://pastebin.com/kU5rPssk

我正在寻找所有 <name>与此正则表达式匹配的标签 \<name\>(\d+ \@.*)\<\/name\>然后操作标签的文本。

这是我用来尝试测试正则表达式的代码:

import re
from bs4 import BeautifulSoup

#Open the KML file.
xmldoc = open('doc.kml', "r+")
soup = BeautifulSoup(xmldoc, "xml")

p = re.compile(r"\<name\>(\d+ \@.*)\<\/name\>")

result = re.findall(p, soup)

print result

我收到以下错误:

Traceback (most recent call last):
File ".\regex_test.py", line 10, in <module>
result = re.findall(p, soup)
File "C:\Python27\lib\re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

我做错了什么?

最佳答案

将正则表达式传递给 text find_all() 的参数:

import re
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('doc.kml'), 'xml')
for name in soup.find_all('name', text=re.compile("\d+ @.*")):
print name

它打印:

<kml:name>13233 @ 2014-05-19 21:35:30 GMT (ACPU)</kml:name>
<kml:name>13233 @ 2014-05-19 21:36:30 GMT (ACPU)</kml:name>
<kml:name>13233 @ 2014-05-19 21:37:30 GMT (ACPU)</kml:name>
...
<kml:name>13233 @ 2014-05-19 22:28:30 GMT (ACPU)</kml:name>

关于python - 找到一个xml标签并将标签名称替换为python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770507/

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