我相信某处有一个 HTML 提取包,但这是我将使用核心 python 和正则表达式模块执行的任务。让txt 成为您呈现的文本<polyline...,所以:
导入正则表达式模块
In [22]: import re
执行搜索:
In [24]: g = re.search('polyline points="(.*?)"', txt)
在上面的正则表达式中,我使用polyline points=" 作为锚点(我省略了<,因为它在正则表达式中具有含义)并捕获所有其余部分,直到下一个引号。
你想要的文字是通过以下方式实现的:
In [25]: g.group(1)
Out[25]: '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280'
更新
使用xml解析数据更安全,这里有一种方法(xml.etree包含在标准库中):
In [32]: import xml.etree.ElementTree as ET
In [33]: root = ET.fromstring(txt)
由于您的数据已经被格式化为根标签,您不需要进一步提取:
In [35]: root.tag
Out[35]: 'polyline'
而且所有的属性实际上都是 XML 属性,转换成字典:
In [37]: root.attrib
Out[37]:
{'points': '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280', 'style': 'fill: none; stroke: #000000; stroke-width: 1; stroke-linejoin: round; stroke-linecap: round; stroke-antialiasing: false; stroke-antialias: 0; opacity: 0.8'}
所以你有它:
In [38]: root.attrib['points']
Out[38]: '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280'
如果您想进一步根据逗号和空格将其拆分为组,我会这样做:
使用不带参数的split 以空格分隔所有组:
>>> p = g.group(1).split()
>>> p
['239,274', '239,274', '239,274', '239,275', '239,275', '238,276', '238,276', '237,276', '237,276', '236,276', '236,276', '236,277', '236,277', '235,277', '235,277', '234,278', '234,278', '233,279', '233,279', '232,280', '232,280', '231,280', '231,280', '230,280', '230,280', '230,280', '229,280', '229,280']
现在对于每个字符串,用逗号将其拆分,这将返回一个字符串列表。我使用map 将每个这样的列表转换为ints 的列表:
>>> p2 = [list(map(int, numbers.split(','))) for numbers in p]
>>> p2
[[239, 274], [239, 274], [239, 274], [239, 275], [239, 275], [238, 276], [238, 276], [237, 276], [237, 276], [236, 276], [236, 276], [236, 277], [236, 277], [235, 277], [235, 277], [234, 278], [234, 278], [233, 279], [233, 279], [232, 280], [232, 280], [231, 280], [231, 280], [230, 280], [230, 280], [230, 280], [229, 280], [229, 280]]
这会带来更多启示:
>>> '123,456'.split(',')
['123', '456']
>>> list(map(int, '123,456'.split(',')))
[123, 456]