【问题标题】:GTFS - how to combine the protocol buffers and GTFS file?GTFS - 如何组合协议缓冲区和 GTFS 文件?
【发布时间】:2014-12-17 17:17:33
【问题描述】:

我正在尝试查看New York City Subway Realtime GTFS Feeds。经过大量阅读,我了解了Protocol Buffers并安装了protoc编译器。

New York City Transit 的文件 nyct-subway.proto.txt 第一行显示 NYCT 地铁对 GTFS 实时协议的扩展。这是否应该与 gtfs-realtime-proto 结合使用?我分别编译了两个协议缓冲区并得到了警告:

[libprotobuf WARNING google/protobuf/compiler/parser.cc:471] 
No syntax specified for the proto file. 
Please use 'syntax = "proto2";' or 'syntax = "proto3";' to specify a syntax version. (Defaulted to proto2 syntax.)

在 Python 中写了一行来调用 protoc 创建的任何库:

import gtfs_realtime_pb2, nyct_subway_pb2

尽管我之前进行了安装,但 Python 对 import google.protobuf 一无所知,所以它知道 sudo pip install protobuf

此时我仍然没有读取任何数据——我可以得到一个不可读的带有http://datamine.mta.info/mta_esi.php?key=<key>&feed_id=1 的 gtfs 文件。

如何结合它从 GTFS 文件中读取数据?

【问题讨论】:

  • 你找到解决办法了吗?
  • nyct-subway.proto 文件依赖于 protoc 编译时的 gtfs-realtime.proto 文件。因此,一旦 protoc 从这些 .proto 文件生成 Python 代码,您应该能够只导入生成的 Python 代码并在代码中使用名为 FeedMessage 或 transit_realtime.FeedMessage 的生成类。当您调用 FeedMessage.FromString(s) 时,此代码会将二进制提要响应解码为一个实例,其中 s 是原始提要响应。

标签: python protocol-buffers gtfs


【解决方案1】:

为了进一步澄清 Jamie 的评论,您应该能够执行以下操作:

import urllib2
import gtfs_realtime_pb2, nyct_subway_pb2

... 

    // initialize the feed parser
    feed = gtfs_realtime_pb2.FeedMessage()

    // fetch the raw gtfs-realtime feed
    gtfs_raw = urllib2.urlopen("http://datamine.mta.info/mta_esi.php?key=<key>&feed_id=1").read()

    // parse the raw feed
    feed.ParseFromString(gtfs_raw)

    // access the data structure as needed
    print feed.header.timestamp
    print feed.header.gtfs_realtime_version

    for entity in feed.entity:
        // etc.

替代方法(命令行 + JSON)

就个人而言,我认为协议缓冲区和 gtfs-realtime 可能会很痛苦。为了跳过这项工作,我编写了一个将 GTFS-realtime 转换为 JSON 的独立工具:
https://github.com/harrytruong/gtfs_realtime_json

只需下载(无需安装),然后运行:gtfs_realtime_json &lt;feed_url&gt;

这是一个示例JSON output

【讨论】:

    【解决方案2】:

    您可以使用protobuf Python 包将两者结合在一起。 下载.proto文件并将其放入docs/gtfs_proto,为输出创建一个gtfs_proto文件夹,然后运行:

    export SRC_DIR=docs/gtfs_proto
    export DST_DIR=gtfs_proto
    protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/nyct-subway.proto
    

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多