【问题标题】:How to clean up .gpx data before writing to a .csv file in python如何在 python 中写入 .csv 文件之前清理 .gpx 数据
【发布时间】:2014-11-28 07:20:44
【问题描述】:

我正在尝试从 .gpx 文件中提取特定数据。 需要的数据是'trkpt'和'ele',即位置和高程数据。 下面列出的代码几乎完成了我需要它做的事情,但它看起来很乱,我只需要数字数据。

gpx_list = []
gpx = open('G:\\14022705.gpx', 'r')  
for line in gpx:
    info = line.split(',')
    if 'trkpt ' in line:
        gpx_list.append(info)
        print line
    if 'ele' in line:
        gpx_list.append(info)
        print line

gpx_list_out = open('G:\\Position_Data2.csv', 'w')  
for line in gpx_list:
    gpx_list_out.write(line[0])

gpx_list_out.close()

输出示例:

['<trkpt lat="-42.6150634" lon="+147.4397831">']
['<ele>1.431</ele>']

相反,我希望它看起来像: -42.6150634, +147.4397831, 1.431都在一条线上

任何有关实现此目的的提示都将不胜感激。我已经尝试了几个小时来添加不同的代码,但未能达到预期的结果!

【问题讨论】:

  • 好的,不知道为什么我的输出示例会这样显示?它应该是这样的:
  • [''] ['1.431']

标签: python-2.7 csv gpx


【解决方案1】:

尝试将其合并到您的代码中。正则表达式提取每一行中的所有数字

import re

gpx_list = []
gpx = open('G:\\14022705.gpx', 'r')      
gpx_list_out = open('G:\\Position_Data2.csv', 'w') 

for line in gpx:
    if 'trkpt ' in line:
      print re.findall(r"[-+]?\d*\.\d+|\d+",line)
      numerical_value=re.findall(r"[-+]?\d*\.\d+|\d+",line)
      gpx_list_out.write(",".join(numerical_value))

gpx_list_out.close()

【讨论】:

  • 谢谢!我已经尝试过了,得到了 ['-42.6150634', '+147.4397831'] ['1.431'],这真的把它整理好了。虽然不想写入 csv 文件,这和以前一样奇怪!
  • @student2014 你的 gpx 文件是什么样子的?可以发一行吗?
  • 这是原始文件的第一位:mikrokopter.de"> MikroKopterFC HW:2.1 SW:2.0a + NC HW:2.0 SW:2.0a desc> 航班1.431
  • 这是你想要的吗?
  • 是的。我更改了代码,但由于您有一个 XML 文件,我建议您使用一些 XML 解析器,例如 Beautifulsoup
猜你喜欢
  • 2013-04-05
  • 2016-12-23
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
相关资源
最近更新 更多