简体   繁体   English

python中来自yaml的csv文件

[英]csv file from yaml in python

4:
- a: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
  b: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
  c: [462, 429, 401, 389]
  d: 1
5:
- e: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994]
  f: [-70.26386506067132, 19.563101216582368, 315.91419304402643]
  g: [462, 429, 401, 389]
  h: 1

This is my yml format and I have to extract only the values of key c and g from it and create a csv file.这是我的 yml 格式,我只需要从中提取键 c 和 g 的值并创建一个 csv 文件。 I am new to python.我是python的新手。
Can anyone guide me here thanks in advance任何人都可以在这里指导我在此先感谢

Through looping you can do but this is just an idea you can have better also通过循环你可以做到,但这只是一个你也可以拥有更好的想法

try this:-试试这个:-

import yaml
MyDict = yaml.load(open('example.yaml'))

    key = ['c','g']
    for i in MyDict.values():
        for j  in i:
            for k in key:
                if k in j:
                    print(j.get(k))

If your yaml converted to dict is similar to this :如果您的 yaml 转换为 dict 类似于:

d = {4:
       {
      'a': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
      'b': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
      'c': [462, 429, 401, 389],
      'd': 1
       },
    5:
     {'e': [0.6511928334730416, -0.6444996859128429, 0.40070930065859994],
      'f': [-70.26386506067132, 19.563101216582368, 315.91419304402643],
      'g': [462, 429, 401, 380],
      'h': 1
     }
    }

The following code you can try to convert the values to CSV :您可以尝试将以下代码转换为 CSV 值:

import csv  
import itertools  

# taking only the values of keys 'c' and 'g'
li = [i[j] for i in d.values()  for j in i.keys()  if j == "c" or j == "g"]

# the above list of list making a flat list for better result
merged = list(itertools.chain.from_iterable(li))

with open("filename.csv",'w') as myfile:
    wr = csv.writer(myfile, lineterminator='\n')
    # If you want first list to csv you can use li instead of merged 
    wr.writerow(merged)

I have tried and tested this我已经尝试并测试了这个

import yaml

with open(r'test.yaml') as file:
    documents = yaml.full_load(file)

for item, doc in documents.items():
    print(item, ":", doc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM