【问题标题】:Best way to parse the data in the below format in python to be stored in sql在python中解析以下格式的数据以存储在sql中的最佳方法
【发布时间】:2014-04-08 17:55:51
【问题描述】:

.txt 文件中的样本数据:-

Pamplona    ['gorasanjuan']
Halifax    ['shippingsaturdaywithlindsey']
Nottinghamshire    ['goodluck']
Eindhoven    ['ngfcompetitie', 'roadtothehoofdklasse']
Rotterdam    ['p2000']
---
---
  1. python 中最合适的库/ap 用于解析以上述格式存储在 .txt 文件中的数据以存储在 sql(在 python 中使用 sqlite)或数据报中?

  2. 哪一个更可取,存储在 sql 数据库中还是存储为数据报? 它将被操纵和导出以用于可视化目的。

【问题讨论】:

    标签: python sqlite parsing


    【解决方案1】:

    您可以使用re 将每一行拆分为键和剩余列表。因为列表是准JSON格式的,你可以使用模块json来解析它们(因此你必须用"替换')。示例:

    import json
    import re
    
    data = dict()
    
    with open("test.txt", "r") as fd:
        for line in fd.readlines():
            m = re.match("^(\w+)(.*)", line)
            data[m.group(1)] = json.loads(m.group(2).replace("'", "\""))
    
    print data
    

    用文件test.txt:

    Pamplona    ['gorasanjuan']
    Halifax    ['shippingsaturdaywithlindsey']
    Nottinghamshire    ['goodluck']
    Eindhoven    ['ngfcompetitie', 'roadtothehoofdklasse']
    Rotterdam    ['p2000']
    

    你得到输出:

    {'Rotterdam': [u'p2000'], 'Halifax': [u'shippingsaturdaywithlindsey'], 'Nottinghamshire': [u'goodluck'], 'Pamplona': [u'gorasanjuan'], 'Eindhoven': [u'ngfcompetitie', u'roadtothehoofdklasse']}
    

    对于数据库,您还可以使用像 levelDB 这样的键值存储。

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 2014-01-25
      • 2016-07-19
      • 2020-07-09
      相关资源
      最近更新 更多