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"(?<=Section )(.*)$"
        section_colons = r"\1 : "
        end_names = "end"
    
        # Convert to YAML format, line-by-line
        for line in lines:
            add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
            remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
            line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections
    
        # Join lines back together
        converted_file = "\n".join(lines)
        return converted_file
    
    4 bằng
    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"(?<=Section )(.*)$"
        section_colons = r"\1 : "
        end_names = "end"
    
        # Convert to YAML format, line-by-line
        for line in lines:
            add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
            remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
            line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections
    
        # Join lines back together
        converted_file = "\n".join(lines)
        return converted_file
    
    5.
  3. Loại bỏ
    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"(?<=Section )(.*)$"
        section_colons = r"\1 : "
        end_names = "end"
    
        # Convert to YAML format, line-by-line
        for line in lines:
            add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
            remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
            line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections
    
        # Join lines back together
        converted_file = "\n".join(lines)
        return converted_file
    
    6 giữa mỗi phần.

Tuy nhiên, tôi gặp khó khăn với #2 và #3. Đây là hàm văn bản-to-yaml mà tôi đã tạo cho đến nay:

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file

Tôi tin rằng vấn đề nằm trong vòng lặp

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file
7 - Tôi không thể tìm ra lý do tại sao các tiêu đề và kết thúc của phần không thay đổi. Nó in hoàn hảo nếu tôi kiểm tra nó, nhưng bản thân các dòng không tiết kiệm.

Định dạng đầu ra mà tôi đang tìm kiếm là như sau:

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

DateTime.Datetime

!! omap, !! cặp

Danh sách các cặp

!!bộ

BộYet Another Markup Language. It stores the configuration file data in a serialized manner; it has gained much popularity in recent years since it is a human-readable data format and is often used in data storage or transmission.

!! seq

danh sách

Ưu điểm của Yaml

Một số lợi thế quan trọng của YAML như sau.

  • Tất cả các ngôn ngữ lập trình đều hỗ trợ YAML - chúng ta cần viết YAML bằng một ngôn ngữ và có thể được sử dụng với hầu hết mọi ngôn ngữ lập trình mà không cần sửa đổi. We need to write YAML in one language and can be used with almost every programming language without any modification.
  • Tính tuần tự hóa đối tượng - Chúng ta có thể tuần tự hóa định dạng dữ liệu YAML. We can serialize the YAML data format.
  • Dễ dàng đọc - không có quy tắc viết cứng để tạo tệp yaml. Một vết lõm đơn giản được sử dụng để xác định khối và tài liệu riêng lẻ. There is no hard-written rule to create a YAML file. A simple indentation is used to define the individual block and documents.

Trước khi bắt đầu xa hơn, chúng tôi cho rằng bạn có một sự hiểu biết cơ bản về trải nghiệm lập trình cấp độ Python hoặc người mới bắt đầu với ngôn ngữ lập trình Python.

Mô -đun pyyaml

Pyyaml ​​là một mô -đun Python cung cấp một loạt các phương thức để thực hiện một số hoạt động trên tệp YAML. Chúng ta có thể dễ dàng chuyển đổi tệp YAML thành từ điển và đọc nội dung của nó. Với sự trợ giúp của mô -đun YAML, chúng ta có thể đọc các tệp YAML Cấu hình phức tạp, tuần tự hóa và dữ liệu YAML tồn tại.

Để sử dụng pyyaml, chúng tôi cần cài đặt nó trong hệ thống của chúng tôi. Dưới đây là các bước cài đặt của mô -đun Pyyaml.

Cài đặt pyyaml

Chúng ta có thể cài đặt nó bằng phương pháp dưới đây.

  • Cài đặt bằng lệnh PIP
  • Cài đặt thông qua mã nguồn

Sử dụng lệnh pip

Chúng ta có thể cài đặt nó bằng lệnh PIP. Nhập lệnh sau vào thiết bị đầu cuối để cài đặt mô -đun pyyaml.

Cài đặt thông qua mã nguồn

Sử dụng lệnh pip

  • Chúng ta có thể cài đặt nó bằng lệnh PIP. Nhập lệnh sau vào thiết bị đầu cuối để cài đặt mô -đun pyyaml.
  • Chúng ta có thể sử dụng cách cài đặt thay thế trong trường hợp đối mặt với lỗi bằng lệnh PIP. Thực hiện theo các hướng dẫn dưới đây.
  • Mở kho Pyyaml ​​GitHub, nhấp vào phần mã và tải xuống tệp zip.
  • Trích xuất tệp zip đã tải xuống.

Bây giờ hãy mở thiết bị đầu cuối và thay đổi thư mục trong đó tệp zip được trích xuất.

Bây giờ chạy lệnh Python Setup.py và nhấn nút Enter. Nó sẽ cài đặt mô -đun Pyyaml ​​trong máy của bạn.sample.yaml file that will use to read using the PyYAML module.

sample.py

Đọc tệp yamlyaml.load() method is used to read the YAML file. This method parses and converts the YAML object to a Python dictionary so that we can read the content easily. This process is called the Deserialization of YAML files into Python.

Đầu tiên, chúng tôi tạo một tệp YAML mới có tên là tệp mẫu.YAML sẽ sử dụng để đọc bằng mô -đun PyyamL.

Phương thức yaml.load () được sử dụng để đọc tệp yaml. Phương pháp này phân tích cú pháp và chuyển đổi đối tượng YAML thành từ điển Python để chúng ta có thể đọc nội dung một cách dễ dàng. Quá trình này được gọi là sự giải phóng của các tệp yaml vào python.

Phương thức Load () có một đối số, có thể là chuỗi byte, đối tượng tệp nhị phân mở, chuỗi unicode hoặc đối tượng tệp yaml mở.

Nếu chúng ta truyền tệp hoặc chuỗi byte như một đối số, nó sẽ được mã hóa trong UTF-8, UTF-16-BE hoặc UTF-16-le.

Output:

[{'UserName': 'Antonio', 'Password': 'fire123 *', 'phone': 9879098, 'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}]

Hãy hiểu ví dụ sau.

Thí dụ -load() function comes with the four types of Loader.

  • Giải trình - We used this Loader in the above example. It loads a subset of the YAML safely. It is mostly used when input is from an untrusted source.
  • Chúng tôi đã nhập YAML và trình tải của nó vào đầu đọc tệp YAML trong mã trên. Hàm tải () đi kèm với bốn loại trình tải. It loads all the basic YAML scalars as Strings.
  • Safeloader - Chúng tôi đã sử dụng trình tải này trong ví dụ trên. Nó tải một tập hợp con của YAML một cách an toàn. Nó chủ yếu được sử dụng khi đầu vào là từ một nguồn không đáng tin cậy. It works the same as BaseLoader but avoids arbitrary code execution. If the input is from an untrusted source, it can pose a security threat.
  • Baseloader - Nó tải tất cả các vô hướng YAML cơ bản dưới dạng chuỗi. It is recommended Loader for untrusted source inputs and is generally used for backward compatibility.

Fullloader - Nó hoạt động giống như Baseloader nhưng tránh được thực thi mã tùy ý. Nếu đầu vào là từ một nguồn không đáng tin cậy, nó có thể gây ra mối đe dọa bảo mật.load() method returned the generator object that we type cased into the list and could access any element.

UNSAEFOADLER - Trình tải được khuyến nghị cho các đầu vào nguồn không đáng tin cậy và thường được sử dụng để tương thích ngược.

Phương thức Load () đã trả về đối tượng Trình tạo mà chúng tôi nhập CASE vào danh sách và có thể truy cập bất kỳ phần tử nào.

Chúng ta cũng có thể nhận được các giá trị tương tự dưới dạng từ điển. Hãy hiểu ví dụ sau.

Output:

{'UserName': 'Antonio', 'Password': 'fire123 *', 'phone': 9879098, 'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}

Chúng ta cũng có thể nhận được các giá trị YAML dưới dạng từ điển. Hãy hiểu ví dụ sau.FullLoader that converted the YAML data into the Dictionary. The advantage of this loader is that, we don't need to type cast the loaded data into list.

Ví dụ - 2

Chúng tôi đã thay đổi đối số vô hướng Safeloader thành Fullloader đã chuyển đổi dữ liệu YAML thành từ điển. Ưu điểm của trình tải này là, chúng ta không cần gõ dữ liệu được tải vào danh sách.yaml.load_all() method. A single YAML file can have multiple documents. Below is the example of multiple documents in single file.

sample.yaml

Đọc nhiều tài liệu YAML

Nếu chúng ta truyền tệp hoặc chuỗi byte như một đối số, nó sẽ được mã hóa trong UTF-8, UTF-16-BE hoặc UTF-16-le.

Output:

[{'UserName': 'Antonio', 'Password': 'fire123 *', 'phone': 9879098, 'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}, {'UserName': 'Maino', 'Password': 'fire123 *', 'phone': 9879098, 'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}, {'UserName': 'George', 'Password': 'fire123 *', 'phone': 9879098, 'Skills': '-Python -SQL -Django -Rest Framework -JavaScript'}]

Hãy hiểu ví dụ sau.

Thí dụ -load() method returned the generator object that we typed cased into the list so we could access any element. In the previous examples, we learned how to read the YAML file. Now we will learn how we can dump data into a YAML file.

Giải trình -

Chúng tôi đã nhập YAML và trình tải của nó vào đầu đọc tệp YAML trong mã trên. Hàm tải () đi kèm với bốn loại trình tải.yaml.dump() method. Let's understand the following example.

Nếu chúng ta truyền tệp hoặc chuỗi byte như một đối số, nó sẽ được mã hóa trong UTF-8, UTF-16-BE hoặc UTF-16-le.

Output:

Password: [email protected]
  Phone: 345464
  Skills:
  - Python
  - SQL
  - Django
  - Rest Framework
  - JavaScript
  User: Zoey
- name: Zaara
  occupation: Dentist

Hãy hiểu ví dụ sau.

Thí dụ -dump() method transforms the Python objects into the YAML format and writes them into the YAML file. We have done same in the above example. The dump() method takes the two arguments - data and stream.

Đối số dữ liệu đại diện cho đối tượng Python sẽ biến thành luồng YAML. Tham số thứ hai là một tệp phải là một tệp văn bản hoặc tệp nhị phân. Dữ liệu luồng YAML được viết trong tên tệp đã cho; Nếu không, dump () sẽ trả về tài liệu được sản xuất.dump() will return the produced document.

Hãy hiểu ví dụ về việc viết dữ liệu python trong tệp.

Ví dụ - 2:

Output:

NewDetails.yaml

- User: Zoey
  Password: [email protected]
  Phone: 345464
  Skills:
  - Python
  - SQL
  - Django
  - Rest Framework
  - JavaScript
- name: Zaara
  occupation: Dentist

Giải trình

Trong ví dụ trên, trước tiên, chúng tôi đã xác định từ điển Python sẽ được viết trong tệp. Sau đó, chúng tôi đã mở tệp chi tiết mới.YAML trong chế độ ghi. Chúng tôi đã sử dụng phương thức Dump () và truyền đối tượng Python dict với hai thẻ khác. Các thẻ này là -

  • default_flow_style - Nó được sử dụng để hiển thị nội dung của khối lồng nhau với thụt lề thích hợp. Theo mặc định, đó là sự thật. Nếu chúng ta đặt giá trị của nó là sai và giá trị bên trong danh sách lồng nhau được hiển thị theo kiểu Flow, nó sẽ hiển thị nội dung của kiểu khối với thụt lề thích hợp. - It is used to display the contents of the nested block with the proper indentation. By default, it is True. If we set its value as false and the value inside the nested lists is shown in the flow style, it will display the block style's content with the proper indentation.
  • Sort_Keys - Nó được sử dụng để sắp xếp các phím theo thứ tự bảng chữ cái. Theo mặc định, đó là sự thật. Nếu chúng ta đặt giá trị của nó là sai, nó sẽ duy trì thứ tự chèn. - It is used to sort the keys in alphabetical order. By default, it is True. If we set its value as false, it will maintain the insertion order.

Hộp nhiều tài liệu YAML

Phương thức yaml.dump_all () được sử dụng để gửi nhiều tài liệu YAML vào một luồng. Phương pháp này lấy một danh sách hoặc trình tạo tạo các đối tượng Python để được tuần tự hóa thành tài liệu YAML và đối số tùy chọn thứ hai dưới dạng tệp mở.yaml.dump_all() method is used to dump multiple YAML documents to a single stream. This method takes a list or generator producing Python objects to be serialized into YAML document and second optional argument as an open file.

Hãy hiểu ví dụ sau.

Thí dụ -

Output:

Using dump() method
- Password: [email protected]
  Phone: 345464
  Skills:
  - Python
  - SQL
  - Django
  - Rest Framework
  - JavaScript
  User: Zoey
- name: Zaara
  occupation: Dentist

Using dump_all() method
Password: [email protected]
Phone: 345464
Skills:
- Python
- SQL
- Django
- Rest Framework
- JavaScript
User: Zoey
---
name: Zaara
occupation: Dentist

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.

Thí dụ -

Output:

import yaml

from yaml.loader import FullLoader
#open yaml file in read
with open('sample.yaml', 'r') as f:
    
    print("Before Sorting?..")
    yaml_data = yaml.load(f, Loader=FullLoader)
    print(yaml_data)

    print("After Sorting......")
    sorted_data = yaml.dump(yaml_data, sort_keys=True)
    print(sorted_data)

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.

Định dạng tệp yaml

  • Mô -đun Pyyaml ​​cung cấp cơ sở để định dạng tệp YAML trong khi viết tài liệu YAML trong đó. Phương thức Dump () hỗ trợ các đối số định dạng khác nhau. Dưới đây là các đối số định dạng. It helps to set the preferred indentation.
  • Tham số - It helps to set the preferred width.
  • thụt lề - nó giúp đặt thụt đầu vào ưa thích. It forces the preferred style for scalars and collections.

Chiều rộng - Nó giúp đặt chiều rộng ưa thích.

Thí dụ -

Output:

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file
0

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.

Chiều rộng - Nó giúp đặt chiều rộng ưa thích.

Thí dụ -

Output:

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file
1

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.

  • Định dạng tệp yaml
  • Mô -đun Pyyaml ​​cung cấp cơ sở để định dạng tệp YAML trong khi viết tài liệu YAML trong đó. Phương thức Dump () hỗ trợ các đối số định dạng khác nhau. Dưới đây là các đối số định dạng.constuct_mapping() method in the created constructor, that will return a Python dictionary corresponding to YAML node. It will return a constructor with the dictionary.
  • Tham số -add_constructor() that transforms a YAML representation graph to a native Python object. A constructor takes an instance of Loader and a node returns Python objects.
  • thụt lề - nó giúp đặt thụt đầu vào ưa thích.

Hãy hiểu ví dụ sau.

Thí dụ -

Output:

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file
2

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.dump() method uses translation while encoding.

Định dạng tệp yamlMô -đun Pyyaml ​​cung cấp cơ sở để định dạng tệp YAML trong khi viết tài liệu YAML trong đó. Phương thức Dump () hỗ trợ các đối số định dạng khác nhau. Dưới đây là các đối số định dạng.
Tham số -thụt lề - nó giúp đặt thụt đầu vào ưa thích.
Chiều rộng - Nó giúp đặt chiều rộng ưa thích.Canonical = true - nó buộc kiểu dáng ưa thích cho vô hướng và bộ sưu tập.
Hãy hiểu ví dụ sau -Lớp Python tùy chỉnh Yaml serializable
Chúng ta có thể tạo lớp Python tùy chỉnh có thể chuyển đổi YAML thành đối tượng Python tùy chỉnh thay vì danh sách hoặc được tích hợp theo các loại.Thẻ tùy chỉnh với pyyaml
Chúng tôi có thể tạo các thẻ tùy chỉnh theo yêu cầu ứng dụng và gán giá trị mặc định cho các thẻ tùy chỉnh trong khi phân tích tệp YAML. Để làm như vậy, nó liên quan đến các bước nhất định được đưa ra dưới đây.Trong bước đầu tiên, chúng tôi xác định hàm tạo hàm lấy Trình tải và nút YAML.
Chúng tôi gọi phương thức Constuct_Mapping () trong hàm tạo đã tạo, sẽ trả về từ điển Python tương ứng với nút YAML. Nó sẽ trả lại một hàm tạo với từ điển.Hàm xây dựng được trả về sẽ được chuyển đến add_constructor () chuyển đổi biểu đồ biểu diễn YAML thành đối tượng Python gốc. Một hàm tạo có một thể hiện của trình tải và một nút trả về các đối tượng Python.
Bây giờ, phương thức tải () có thể chấp nhận nhiều trường theo yêu cầu với cùng một thẻ tùy chỉnh được xác định trong add_constructor (). Các trường không có giá trị sẽ được phân bổ các giá trị mặc định được xác định trong phương thức __init __ ().Bảng chuyển đổi trong mô -đun Pyyaml
Dưới đây là bảng mà mô -đun Pyyaml ​​sử dụng để chuyển đổi các đối tượng Python thành tương đương YAML. Phương thức Dump () sử dụng dịch trong khi mã hóa.Thẻ yaml
Loại Python!!vô giá trị
Không có!! bool
Bool!!trôi nổi

Trôi nổi

!! intYAMLError in case of any error. With the help of this error, we can debug the problem. So it is recommended to use the YAML serialization code in the try-expect block. Let's understand the following example.

Thí dụ -

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.scan() method to produce a set of tokens. Let's understand the following example.

Thí dụ -

Output:

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"(?<=Section )(.*)$"
    section_colons = r"\1 : "
    end_names = "end"

    # Convert to YAML format, line-by-line
    for line in lines:
        add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
        remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
        line = re.sub(end_names, "", remove_section_word)          # Remove "end" between sections

    # Join lines back together
    converted_file = "\n".join(lines)
    return converted_file
3

Python Yaml Sắp xếp các phím

Sort_Keys là một thẻ tùy chọn được sử dụng trong khi bỏ dữ liệu Python vào tệp. Nếu chúng ta đặt nó là đúng, nó sẽ sắp xếp tất cả các khóa của các tài liệu YAML theo thứ tự bảng chữ cái. Hãy hiểu ví dụ sau.XMLPlain module. XML is an abbreviation name of eXtensible Markup Language which uses HTML tags to define tags.

Định dạng tệp yamlobj_from_yaml() method is used generate the XML plain obj from the YAML stream or string. To keep the XML plain object element in order, YAML streams are stored as the OrderDict.

Hãy lấy tệp YAML mẫu với chi tiết nhân viên và chuyển đổi nó thành tệp XML.

Thí dụ -

Hãy hiểu việc thực hiện mã.

Thí dụ -

Hãy hiểu việc thực hiện mã.

Sự kết luậnPyYAML modules. We covered how to create custom tags, loading the contents of a YAML file into our Python program as dictionaries. We have also discussed how to manipulate YAML formatted files. This tutorial is included quite a brief and basic functionality of the library.


Trong hướng dẫn này, chúng tôi đã học được một số khái niệm quan trọng về các mô -đun Yaml và Pyyaml. Chúng tôi đề cập đến cách tạo các thẻ tùy chỉnh, tải nội dung của tệp yaml vào chương trình Python của chúng tôi dưới dạng từ điển. Chúng tôi cũng đã thảo luận về cách thao tác các tệp được định dạng YAML. Hướng dẫn này được bao gồm một chức năng khá ngắn gọn và cơ bản của thư viện.Effective Root Searching Algorithms in Python

Tiếp theo thuật toán tìm kiếm gốc Topiceffective trong Python

Làm cách nào để viết một tệp yaml bằng python?

Viết tệp yaml trong python open config.py và thêm các dòng mã sau ngay bên dưới phương thức read_yaml và phía trên khối chính của tệp. Trong phương thức write_yaml, chúng tôi mở một tệp có tên Toyaml. YML ở chế độ ghi và sử dụng phương thức kết xuất của các gói YAML để ghi tài liệu YAML vào tệp.Open config.py and add the following lines of code just below the read_yaml method and above the main block of the file. In the write_yaml method, we open a file called toyaml. yml in write mode and use the YAML packages' dump method to write the YAML document to the file.

Làm cách nào để tạo tệp yaml?

Đây là 3 cách để tạo một tệp yaml mới ...
Nhận tệp mẫu cấu hình YAML, chẳng hạn như mẫu tệp chơi ansible.Đây là nginx-deplymnet.yaml ..
Sử dụng trình soạn thảo văn bản hoặc công cụ trực tuyến để tạo cú pháp / cấu trúc YAML ..
Tạo một tệp từ URL YAML ..

Yaml ở Python là gì?

YAML (YAML không phải là ngôn ngữ đánh dấu) là ngôn ngữ chủ yếu hóa dữ liệu có thể đọc được của con người.Nó thường được sử dụng cho các tệp cấu hình, nhưng nó cũng được sử dụng trong lưu trữ dữ liệu (ví dụ: đầu ra gỡ lỗi) hoặc truyền (ví dụ: tiêu đề tài liệu).a human-readable data-serialization language. It is commonly used for configuration files, but it is also used in data storage (e.g. debugging output) or transmission (e.g. document headers).

Dump Yaml là gì?

Việc bán phá giá YAML chấp nhận đối số tùy chọn thứ hai, phải là một văn bản mở hoặc tệp nhị phân.Trong trường hợp này, Yaml.Dump sẽ viết tài liệu YAML được sản xuất vào tệp.Nếu không, Yaml.Dump trả về tài liệu sản xuất.write the produced YAML document into the file. Otherwise, yaml. dump returns the produced document.