使用正则表达式从GML CityJSON提取数值遇阻求助
问题分析与解决方案
你的正则操作可能踩了这些坑
标签匹配失败的常见原因:
- 标签内容换行:你用的
.*?默认不匹配换行符,如果<bldg:lod2TerrainIntersection>和闭合标签之间的内容换行了,正则就抓不到。可以给正则加单行模式(比如Python里用re.DOTALL),或者把正则改成(?s)<bldg:lod2TerrainIntersection>(.*?)</bldg:lod2TerrainIntersection>。 - 标签存在空格或大小写差异:比如文件里的标签是
<bldg:lod2TerrainIntersection >(闭合标签前有空格),或者前缀不是bldg,正则里的硬编码就匹配不上。 - CityJSON与GML的结构混淆:CityJSON本身是JSON格式,如果文件是CityJSON而非纯GML,那你找的标签根本不存在。
- 标签内容换行:你用的
数值提取失败的原因:
- 你的正则
\d+\.\d+匹配不了带负号的数值(比如-123.4567),应该改成-?\d+\.\d+。 - 如果数值被嵌套在JSON数组或对象里,直接全局匹配会抓到无关的数值,必须先定位到正确的上下文再提取。
- 你的正则
更靠谱的实现方案
别用正则处理GML/CityJSON这种结构化格式,用专门的解析工具才是正道:
处理CityJSON(JSON格式)
如果是标准CityJSON文件,直接用JSON解析库:
import json with open("your_file.city.json", "r") as f: data = json.load(f) # 根据实际文件结构遍历,假设数值在lod2TerrainIntersection的边界坐标中 for feature in data.get("CityObjects", {}).values(): geom = feature.get("geometry", [{}])[0] if "lod2TerrainIntersection" in geom.get("type", ""): for boundary in geom.get("boundaries", []): for coord_group in boundary: for num in coord_group: # 筛选xxx.xxxx格式的数值 num_str = str(num) if "." in num_str and len(num_str.split(".")[0].lstrip("-")) == 3 and len(num_str.split(".")[1]) == 4: print(num)
处理GML格式
如果是纯GML文件,用XML解析库比如lxml:
from lxml import etree import re tree = etree.parse("your_file.gml") # 从文件的xmlns:bldg属性中获取对应的命名空间,替换下面的URL namespaces = {"bldg": "http://www.opengis.net/citygml/building/2.0"} # 提取所有目标标签的文本内容 elements = tree.xpath("//bldg:lod2TerrainIntersection/text()", namespaces=namespaces) for text in elements: # 提取数值并筛选格式 nums = re.findall(r"-?\d+\.\d+", text) filtered_nums = [num for num in nums if len(num.split(".")[0].lstrip("-")) == 3 and len(num.split(".")[1]) == 4] print(filtered_nums)
内容的提问来源于stack exchange,提问作者pcace
相关产品推荐
相关产品推荐

