Hướng dẫn convert text to yaml python - chuyển đổi văn bản sang yaml python

Tôi có một tệp văn bản để chuyển đổi sang định dạng YAML. Dưới đây là một số ghi chú để mô tả vấn đề tốt hơn một chút:

  • Các phần trong tệp có một số đầu phụ khác nhau với nhau.
  • Các giá trị của các tiêu đề phụ có thể là bất kỳ loại dữ liệu nào [ví dụ: chuỗi, bool, int, double, dateTime].
  • Các tập tin dài khoảng 2.000 dòng.

Một ví dụ về định dạng dưới đây:

file_content = '''
    Section section_1
        section_1_subheading1 = text
        section_1_subheading2 = bool
    end
    Section section_2
       section_2_subheading3 = int
       section_2_subheading4 = double
       section_2_subheading5 = bool
       section_2_subheading6 = text
       section_2_subheading7 = datetime
    end
    Section section_3
       section_3_subheading8 = numeric
       section_3_subheading9 = int
    end
'''

Tôi đã cố gắng chuyển đổi văn bản thành định dạng YAML bằng cách:

  1. Thay thế các dấu hiệu bằng nhau bằng các dấu hiệu bằng Regex.
  2. Thay thế
    import yaml
    import re
    
    def convert_txt_to_yaml[file_content]:
        """Converts a text file to a YAML file"""
    
        # Replace "=" with ":"
        file_content2 = file_content.replace["=", ":"]
    
        # Split the lines 
        lines = file_content2.splitlines[]
    
        # Define section headings to find and replace
        section_names = "Section "
        section_headings = r"[?

Bài Viết Liên Quan

Chủ Đề