代码之家  ›  专栏  ›  技术社区  ›  erotsppa

从googleappengine中的文件生成json的正确方法是什么?

  •  1
  • erotsppa  · 技术社区  · 15 年前

    我对python和gae很陌生,有人能为完成以下简单任务提供一些帮助/示例代码吗?我设法读取了一个简单的文件并将其作为网页输出,但我需要一些稍微复杂一些的逻辑。以下是伪代码:

      open file;
      for each line in file {
        store first line as album title;
        for each song read {
          store first line as song title;
          store second line as song URL;
        }
      }
      Output the read in data as a json;
    

    文件格式如下

    专辑标题1
    宋题
    歌曲1网址
    歌曲2标题
    Song2网址

    专辑TILL2
    宋题
    歌曲1网址
    歌曲2标题
    歌曲2网址

    2 回复  |  直到 15 年前
        1
  •  3
  •   Kenan Banks    15 年前

    下面是一个基于生成器的解决方案,它有一些好的特性:

    • 允许文本文件中相册之间有多个空行
    • 允许文本文件中的前导/尾随空行
    • 一次只使用一张专辑的内存
    • 演示了许多可以用python进行的neato操作:)

    相册

    Album title1
    song1 title
    song1 url
    song2 title
    song2 url
    
    Album title2
    song1 title
    song1 url
    song2 title
    song2 url
    

    代码

    from django.utils import simplejson
    
    def gen_groups(lines):
       """ Returns contiguous groups of lines in a file """
    
       group = []
    
       for line in lines:
          line = line.strip()
          if not line and group:
             yield group
             group = []
          elif line:
             group.append(line)
    
    
    def gen_albums(groups):
       """ Given groups of lines in an album file, returns albums  """
    
       for group in groups:
          title    = group.pop(0)
          songinfo = zip(*[iter(group)]*2)
          songs    = [dict(title=title,url=url) for title,url in songinfo]
          album    = dict(title=title, songs=songs)
    
          yield album
    
    
    input = open('albums.txt')
    groups = gen_groups(input)
    albums = gen_albums(groups)
    
    print simplejson.dumps(list(albums))
    

    产量

    [{"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
    title"},
    {"songs": [{"url": "song1 url", "title": "song1 title"}, {"url": "song2 url", "title": "song2 title"}], "title": "song2
    title"}]
    

    然后可以在javascript中访问相册信息,如下所示:

    var url = albums[1].songs[0].url;
    

    最后,这是一个关于 tricky zip line .

        2
  •  1
  •   Alex Martelli    15 年前
    from django.utils import simplejson
    
    def albums(f):
      "" yields lists of strings which are the
         stripped lines for an album (blocks of
         nonblank lines separated by blocks of
         blank ones.
      """
      while True:
        # skip leading blank lines if any
        for line in f:
          if not line: return
          line = line.strip()
          if line: break
        result = [line]
        # read up to next blank line or EOF
        for line in f:
          if not line:
            yield result
            return
          line = line.strip()
          if not line: break
          result.append(line)
        yield result
    
    def songs(album):
      """ yields lists of 2 lines, one list per song.
      """
      for i in xrange(1, len(album), 2):
        yield (album[i:i+2] + ['??'])[:2]
    
    result = dict()
    f = open('thefile.txt')
    for albumlines in albums(f):
      current = result[albumlines[0]] = []
      for songlines in songs(albumlines):
        current.append( {
          'songtitle': songlines[0],
          'songurl': songlines[1]
        } )
    
    response.out.write(simplejson.dumps(result))