简体   繁体   English

将文本文件转换为 python 中的 yaml

[英]Convert text file to yaml in python

I have a text file in the below format:我有以下格式的文本文件:

{'Server Type: ABCDDEER' :['name: abcd01t' ,'IP: 127.12.32.52', 'tags: ALL, APP,EER, REER1']},
{'Server Type: ABCDDEER' :['name: abcd02t' ,'IP: 127.12.32.53', 'tags: ALL, APP,EER, REER2']},
{'Server Type: ABCDDEER' :['name: abcd03t' ,'IP: 127.12.32.54', 'tags: ALL, APP,EER, REER1']},
{'Server Type: ABCDDEER' :['name: abcd04t' ,'IP: 127.12.32.55', 'tags: ALL, APP,EER, REER2']},
{'Server Type: ABCDDPP' :['name: abcd1t' ,'IP: 127.12.32.36', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd2t' ,'IP: 127.12.32.37', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd3t' ,'IP: 127.12.32.38', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd4t' ,'IP: 127.12.32.39', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd5t' ,'IP: 127.12.32.47', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd6t' ,'IP: 127.12.32.41', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd7t' ,'IP: 127.12.32.42', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd8t' ,'IP: 127.12.32.48', 'tags: ALL, APP,PP,  PP2']},
{'Server Type: ABCDDPP' :['name: abcd9t' ,'IP: 127.12.32.44', 'tags: ALL, APP,PP,  PP1']},
{'Server Type: ABCDDPP' :['name: abcd0t' ,'IP: 127.12.32.49', 'tags: ALL, APP,PP,  PP2']}

Is there any way we can directly convert to yaml so that it could be in the below format:有什么方法可以直接转换为 yaml 以便它可以采用以下格式:


"Server Type: ABCDDEER"
: 
  - "name: abcd01t"
  - "IP: 127.12.32.52"
  - "tags: ALL, APP,EER, REER1"

  - "name: abcd02t"
  - "IP: 127.12.32.53"
  - "tags: ALL, APP,EER, REER2"

  - "name: abcd03t"
  - "IP: 127.12.32.54"
  - "tags: ALL, APP,EER, REER2"

"Server Type: ABCDDPP"
: 
  - "name: abcd1t"
  - "IP: 127.12.32.36"
  - "tags: ALL, APP,PP,  PP1"

etc ETC

So that the serverTyoe is the header and whatever with same serverType comes inside of it.因此 serverTyoe 是 header 并且其中包含相同 serverType 的任何内容。

Any help will be much appreciated.任何帮助都感激不尽。 Thanks very much!非常感谢!

Using yaml module.使用yaml模块。

Ex:前任:

import ast
import yaml

result = {}
with open("data.txt") as infile:
    for line in infile:
        d = ast.literal_eval(line.strip().rstrip(","))
        for k, v in d.items():
            result.setdefault(k, []).extend(v)     #groupby header

with open("outfile.yaml", 'w') as yfile:
    yaml.dump(result, yfile)

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

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