【问题标题】:csv file from yaml in pythonpython中来自yaml的csv文件
【发布时间】:2018-07-27 06:12:44
【问题描述】:
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

这是我的 yml 格式,我只需要从中提取键 c 和 g 的值并创建一个 csv 文件。我是 python 新手。
谁能在这里指导我 提前致谢

【问题讨论】:

  • 那是两个yaml文件吗?
  • 没有一个
  • 当您遇到问题时,我们会在这里为您提供指导,而不是通过给您答案来指导您。您尝试过吗?
  • 是的..我尝试将其转换为字典.. import yaml ...: MyDict = yaml.load(open('filepath)) 然后我可以通过执行访问每个键值对MyDIct[keyvalue] 但它会打印第 1 节中的整个小节,但我只需要每个部分的第三个值......这里有点困惑
  • 能否请您编辑问题并添加您尝试过的内容。它将帮助其他人更好地了解您的问题

标签: python csv yaml


【解决方案1】:

通过循环你可以做到,但这只是一个你可以更好的想法

试试这个:-

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))

【讨论】:

    【解决方案2】:

    如果你的 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
         }
        }
    

    您可以尝试以下代码将值转换为 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)
    

    【讨论】:

      【解决方案3】:

      我已经试过了

      import yaml
      
      with open(r'test.yaml') as file:
          documents = yaml.full_load(file)
      
      for item, doc in documents.items():
          print(item, ":", doc)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 2014-10-11
        • 1970-01-01
        • 2021-08-20
        • 2021-01-10
        相关资源
        最近更新 更多