怎么样从一个含有 xml 标签的字符串中截取内容

2015-08-31 18:15:30 +08:00
 adrianzhang
一个字符串,含有标签。如下所示:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello, how can I get to the railway station?</string>

问题:
这个内容(本例中是:“ Hello .... station?”)是变化的。
想只把内容取出来,也就是不要那些标签, Python 好像没有什么简单的办法?大家有没有好主意,一两条语句搞定,最好只使用标准库。
3967 次点击
所在节点    Python
25 条回复
abelyao
2015-08-31 18:19:44 +08:00
正则表达式…
seki
2015-08-31 18:22:21 +08:00
adrianzhang
2015-08-31 18:38:57 +08:00
@abelyao
@seki
谢谢两位帮忙。我想到了一个简单的办法:取这个字符串的[68:-9]
abelyao
2015-08-31 18:40:50 +08:00
@adrianzhang 如果确定标签、以及标签属性都是固定的,那这样确实是最方便的
secondwtq
2015-08-31 18:44:40 +08:00
@adrianzhang 总感觉这样好奇怪...

先不说标签发生变化的情况,这个读起来貌似不是很直观...
adrianzhang
2015-08-31 18:46:21 +08:00
@secondwtq
@abelyao

标签不变。想了很多方法,解析 xml 啦,解析 html 啦,等等,都好复杂。只有这方法能一条语句解决问题。
abelyao
2015-08-31 18:48:56 +08:00
@adrianzhang 正则也是一句搞定,思路就是取第一个 <> 开始的内容,到最后一个 </> 结束之前。
iniwap
2015-08-31 18:50:11 +08:00
。。。太不优雅了
firemiles
2015-08-31 18:53:53 +08:00
str1.replace ('<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">','').replace ('</string>','')
是不是更好看点
adrianzhang
2015-08-31 19:35:47 +08:00
@abelyao show me the code?
@firemiles 嗯嗯,好看!我去 test test 。
@iniwap 给个优雅的办法?
em70
2015-08-31 19:38:19 +08:00
#提取任意两个字符串之间的内容
def txt_wrap_by (html,start_str, end,y ):
start = html.find (start_str )
if start >= 0:
start += len (start_str )
end = html.find (end, start )
if end >= 0:
return html[start:end].strip ()
adrianzhang
2015-08-31 19:52:21 +08:00
@firemiles 在双引号前加反斜杆转义一下就 OK 了。这个写法真好!

@em70 嗯嗯,谢谢。想用一两句语句解决这问题。
abelyao
2015-08-31 19:55:22 +08:00
@adrianzhang 思路都说了还 show me the code 呵呵
em70
2015-08-31 20:00:41 +08:00
@adrianzhang 函数都给你定义了,不就是 txt_wrap_by 一行代码搞定了吗,python 没有这种内置函数,PHP 有,要不你换个语言?
adrianzhang
2015-08-31 20:12:30 +08:00
@em70 明白了。谢谢。
zhicheng
2015-08-31 20:13:52 +08:00
烂代码和烂系统就是这么来的。
secondwtq
2015-08-31 20:24:45 +08:00
感觉有时候总是要 oneliner 不是什么好习惯呢。

借一下 2 楼的资料:

import xml.etree.ElementTree
xml.etree.ElementTree.fromstring ('<somestring>').text
hsyu53
2015-08-31 20:26:30 +08:00
lxml 专干个事的
bbking
2015-08-31 20:33:05 +08:00
xml.dom, lxml 都可以
adrianzhang
2015-08-31 21:19:44 +08:00
@secondwtq 原来是这样实现?!没提问题之前看这个库看得头晕。终于找到我认为的最优解了。多谢! 10 个铜板奉上!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/217383

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX