2016-11-17 91 views
1

我在文本文件中的一些数据如下所示图像(它的整个数据的只是一部分)。什么是过滤出密钥的最佳方式?从提取的文本数据的某些部分为CSV使用Python

{ u'chan': 5, 
    u'cls': 0, 
    u'codr': u'4/5', 
    u'data': u'ABfxqqqpVVVOAAA=' 
} 
+0

不链接到图片..在您的问题中复制和粘贴示例数据。显示您尝试过的代码?你能用python读取文本文件吗?你能提取字典吗?你知道如何用python编写文件吗? –

+0

查找ast.eval python模块。它可以让你把你的字典作为一个字符串,并将其转换为一个Python字典。 –

回答

0

对于你贴什么形式的一系列文件的尝试

import csv 
filenames=[...] 
#open your output file in append mode 

with open('output.csv','a+') as out: 
    outwriter = csv.writer(out,dialect='excel') 

#write your headers 
outwriter.writerow(['header1','header2','header3']) 

#for every file 
for fname in filenames: 
    with open(fname) as f: 

     #list that holds each row 
     csvlines=[] 

     #labels you wanna keep 
     keep=["u'data'","u'rssi'","u'timestamp'"] 
     lines=f.readlines() 
     print lines 

     #split at first : character 
     lines = map(lambda x:x.split(':',1),lines) 

     for line in lines: 
      if line[0].strip() in keep: 

       csvlines.append(line[1].strip()) 
    #clean from unnecessary characters 
      csvlines=map(lambda x:x.replace("u'","").replace("'","").replace(",",""),csvlines) 
    #write it to csv and then reset it for the next file. 
      if(len(csvlines)==3): 
       print "writing" 
       print csvlines 
       outwriter.writerow(csvlines) 
       csvlines=[] 
+0

嗨,我有一个文件包含了很多相同格式的数据。它是如何工作的呢? – James

+0

重置每3个附加? – themistoklik

+0

即时获取ValueErrorr:'wa'的无效模式 – James

1

假设样本数据是数据的一个记录,您可以用熊猫直接子集,并导出到Excel工作簿。

import pandas as pd 

df = pd.DataFrame({ u'chan': 5, 
    u'cls': 0, 
    u'codr': u'4/5', 
    u'data': u'ABfxqqqpVVVOAAA=', 
    u'datr': u'SF10BW125', 
    u'freq': u'912.9', 
    u'lsnr': u'-8.2', 
    u'mhdr': u'8007000002001900', 
    u'modu': u'LORA', 
    u'opts': u'', 
    u'port': 5, 
    u'rfch': 1, 
    u'rssi': -111, 
    u'seqn': 25, 
    u'size': 16, 
    u'timestamp': u'2016-11-17T09:51:44.406724Z', 
    u'tmst': 2477375724L},index=[0]) 
df = df[['data','chan','timestamp','rssi']] 
oName = #Path to desired excel workbook 
df.to_excel(oName,'Sheet1') 
+0

示例数据只是我的文本文件的一部分。我确实有其中的多个 – James