在另一个转换字符串结构

时间:2019-10-19 13:53:39

标签: python string shell

我有一个具有这种模式的文件:

import tkinter
from PIL import Image, ImageTk
import base64
import pandas as pd

i = 0
def load_next_img():
    global pil_image, tk_image, i, text

    i = i+1
    base64string = df_slides["Slide_Image"][i]
    imgdata = base64.b64decode(base64string)
    pil_image =  Image.open(io.BytesIO(imgdata))
    tk_image = ImageTk.PhotoImage(pil_image)
    label['image'] = tk_image

    text = df_slides["Text"][i]



def load_previous_img():
    global pil_image, tk_image, i, text

    i = i-1
    base64string = df_slides["Slide_Image"][i]
    imgdata = base64.b64decode(base64string)
    pil_image =  Image.open(io.BytesIO(imgdata))
    tk_image = ImageTk.PhotoImage(pil_image)
    label['image'] = tk_image

    text = df_slides["Text"][i]





root = tkinter.Tk()
label = tkinter.Label(root)
label.pack(side = "bottom", fill = "both", expand = "yes")
load_next_img()

nextbutton = tkinter.Button(text="next", command=load_next_img)
nextbutton.pack()
backbutton = tkinter.Button(text="back", command=load_previous_img)
backbutton.pack()

T = tkinter.Text(root, height=10, width=30)
T.pack()
T.insert(tkinter.END, text)


root.mainloop()

我想将此模式转换为类似文本的文本:

[account.invoice.set_num]
job_size = 0
trans_size = 100

[commission.invoice_second.create_full]
j_size = 0

[commission.invoice_principal.finalize]
j_size = 12
in_directory = /to/the/directory

我尝试在Bash Unix或Python中做到这一点。 我不知道什么是最好/最简单的方法。

1 个答案:

答案 0 :(得分:1)

使用config.ConfigParser功能非常可行:

from configparser import ConfigParser

config = ConfigParser()
config.read('yourfile')

config_lines = ''
for section in config.sections():
    s_key = section.replace('.', '_')   # transformed section key
    for k, v in config.items(section):
        config_lines += f'{s_key}_{k}'.upper() + f'={v}\n'

print(config_lines)

输出:

ACCOUNT_INVOICE_SET_NUM_JOB_SIZE=0
ACCOUNT_INVOICE_SET_NUM_TRANS_SIZE=100
COMMISSION_INVOICE_SECOND_CREATE_FULL_J_SIZE=0
COMMISSION_INVOICE_PRINCIPAL_FINALIZE_J_SIZE=12
COMMISSION_INVOICE_PRINCIPAL_FINALIZE_IN_DIRECTORY=/to/the/directory