【问题标题】:Convert Excel to Yaml syntax in Python在 Python 中将 Excel 转换为 Yaml 语法
【发布时间】:2020-12-15 05:39:46
【问题描述】:

我想将这种形式的数据转换为 YAML 语法(最好不使用 pandas 或不需要安装新库)

excel中的示例数据:

users | name | uid | shell

user1 | nino | 8759 | /bin/ksh

user2 | vivo | 9650 | /bin/sh

所需的输出格式: YAML Syntax output

【问题讨论】:

  • 我是 Mac OS / Ubuntu,所以不要碰 Excel。但是pyyaml 我用于为我的 Ubuntu 配置构建 YAML,可与字典和列表互换
  • 即使不接触pyyaml 或 Pandas,这也不难做到。但是,如果您的输入文件是 Excel,您将需要例如xlrdopenpyxl 阅读;如果是例如CSV,您可以使用内置的csv 库。到目前为止,您尝试过什么?

标签: python json excel pandas yaml


【解决方案1】:

您可以这样做,在您的情况下,您只需使用 pd.read_excel 而不是 pd.read_csv

df = pd.read_csv('test.csv', sep='|')
df['user_col'] = 'users'
data = df.groupby('user_col')[['users', 'name','uid','shell']].apply(lambda x: x.set_index('users').to_dict(orient='index')).to_dict()
with open('newtree.yaml', "w") as f:
    yaml.dump(data, f)

Yaml 文件如下所示:

users:
  user1:
    name: nino
    shell: /bin/ksh
    uid: 8759
  user2:
    name: vivo
    shell: /bin/sh
    uid: 9650

【讨论】:

    【解决方案2】:

    您可以使用文件操作来做到这一点。由于您热衷于 *“最好不要使用 pandas 或不需要安装新库

    假设:“|”符号是表示列,不是分隔符或分隔符

    步骤 1

    Save the excel file as CSV
    

    然后运行代码

    代码

    # STEP 1  : Save your excel file as CSV
    
    ctr = 0
    excel_filename = "Book1.csv"
    yaml_filename = excel_filename.replace('csv', 'yaml')
    users = {}
    
    with open(excel_filename, "r") as excel_csv:
        for line in excel_csv:
            if ctr == 0:
                ctr+=1  # Skip the coumn header
            else:
                # save the csv as a dictionary
                user,name,uid,shell = line.replace(' ','').strip().split(',')
                users[user] = {'name': name, 'uid': uid, 'shell': shell}
    
    
    
    with open(yaml_filename, "w+") as yf :
        yf.write("users: \n")
        for u in users:
            yf.write(f"  {u} : \n")
            for k,v in users[u].items():
                yf.write(f"    {k} : {v}\n")
    
    

    输出

    users: 
      user1 : 
        name : nino
        uid : 8759
        shell : /bin/ksh
      user2 : 
        name : vivo
        uid : 9650
        shell : /bin/sh
    

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 2019-09-15
      • 2021-07-21
      • 2016-02-16
      • 1970-01-01
      • 2021-08-13
      • 2019-03-16
      • 2021-02-10
      • 2021-12-25
      相关资源
      最近更新 更多