Hướng dẫn add header in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file. 

    In this article, we are going to add a header to a CSV file in Python.

    Method #1: Using header argument in to_csv() method.

    Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.

    The following CSV file gfg.csv is used for the operation:

    Hướng dẫn add header in python

    Python3

    import pandas as pd

    file = pd.read_csv("gfg.csv")

    print("\nOriginal file:")

    print(file)

    headerList = ['id', 'name', 'profession']

    file.to_csv("gfg2.csv", header=headerList, index=False)

    file2 = pd.read_csv("gfg2.csv")

    print('\nModified file:')

    print(file2)

    Output: 

    Hướng dẫn add header in python

    The CSV file gfg2.csv is created:

    Hướng dẫn add header in python

    Method #2: UsingDictWriter() method

    Another approach of using DictWriter() can be used to append a header to the contents of a CSV file. The fieldnames attribute can be used to specify the header of the CSV file and the delimiter argument separates the values by the delimiter given in csv module is needed to carry out the addition of header. The writeheader() method is then invoked on csvwriter object, without passing any arguments.

    Python3

    import pandas as pd

    import csv

    headerList = ['col1', 'col2', 'col3', 'col4']

    with open("gfg3.csv", 'w') as file:

        dw = csv.DictWriter(file, delimiter=','

                            fieldnames=headerList)

        dw.writeheader()

    fileContent = pd.read_csv("gfg3.csv")

    fileContent

    Output:

    Hướng dẫn add header in python

    The new CSV file gfg3.csv created is:

    Hướng dẫn add header in python

    Note: This method is only applicable to empty CSV files.


    Microsoft Word (MS)- một trong các tiện ích từ bộ Microsoft Office là một trong những phần mềm phổ biến trong việc tạo ra file document, hỗ trợ đọc và ghi nội dung từ đơn giản đến phức tạp. Mặc dù con người có thể trực tiếp tạo và viết nội dung lên file MS, tuy nhiên trong rất nhiều tác vụ cần máy tính xử lý và tự động tạo nội dung trên các file MS. Ví dụ bạn đọc nội dung từ file pdf và muốn chuyển nội dung sang file docx hoặc bạn đang phát triển một mô hình xử lý ngôn ngữ tự nhiên và cần đọc dữ liệu đầu vào là các file MS thì Python-Docx là một trong những thư viện rất đáng để bạn lựa chọn.

    Nội dung chính

    • 1. Cài đặt thư viện
    • 2. Khởi tạo file
    • 3. Heading, title
    • 3.2. Heading
    • 4. Đoạn văn (paragraph)
    • 4.1. Layout truyền thống
    • 4.2. Layout dạng cột
    • 4.3. Thêm câu cho đoạn văn
    • 4.3.1. Highlight background
    • Lời kết

    Hôm nay mình xin giới thiệu các bạn cách tạo ra tự động file MS cũng như các tính năng thêm, sửa, xóa các nội dung dưới sự hỗ trợ của thư viện Python Docx.

    1. Cài đặt thư viện

    Nếu các bạn đang sử dụng anaconda, các bạn có thể dễ dàng cài đặt bằng cách sau đây:

    pip install python-docx
    

    2. Khởi tạo file

    Để mở một file đã tồn tại trước đó, bạn sử dụng câu lệnh sau

    from docx import Document
    
    document = Document('existing-document-file.docx')
    

    Nếu file này chưa tồn tại, bạn sử dụng câu lệnh sau:

    document = Document()
    

    Sau khi bạn khởi tạo file, bạn có thể chỉnh sửa nội dung của file MS như thêm đoạn văn, thêm bảng, ... thông qua biến document như ví dụ bên trên. Sau khi hoàn thiện bạn có lưu lại những thay đổi bằng câu lệnh sau :

    document.save(filename)
    

    Ở đây, filename là tên file mà bạn muốn lưu. Tất nhiên đuôi là .docx nhé.

    3. Heading, title

    Thư viện python-docx hỗ trợ ghi phần title hoặc heading của văn bản theo nhiều level mà người dùng chỉ định.

    • Content: nội dung title hoặc heading
    • Level: bậc của heading (0, 1, 2, ...). Số càng nhỏ font chữ càng lớn.
    document.add_heading(content, level)
    

    3.1. Title

    Theo mặc định của python-docx, title có level là 0

    document.add_heading("This is a title part, level=0)
    

    Ta có kết quả tương ứng sẽ là :

    3.2. Heading

    Đối với các phần heaing, ta có các level 1, 2, 3....

    • Level 1
    document.add_heading("This is a heading 1", level=1)
    

    Kết quả tương ứng :

    • Level 2
    document.add_heading("This is a heading 2", level=2)
    

    Kết quả tương ứng :

    4. Đoạn văn (paragraph)

    Trong các loại văn bản thông thường, chúng ta có hai cách biểu diễn nội dung của một trang đó là:

    4.1. Layout truyền thống

    Với layout kiểu truyền thống, chúng ta ghi nội dung vào file MS như sau:

    document.add_paragraph(content)
    

    Kết quả tương ứng:

    4.2. Layout dạng cột

    Để tạo ra được các văn bản dạng cột. Chúng ta cần dùng đến khái niệm Section. Mỗi section có thể chứa nhiều các đoạn văn. Mỗi section sẽ tương đương với một page và chúng ta thông qua section để biểu diễn nội dung cho một page.

    Tạo layout cột cho section :

    from docx.enum.section import WD_SECTION_START
    
    def set_number_of_columns(section, cols):
        """ sets number of columns through xpath. """
        WNS_COLS_NUM = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}num"
        section._sectPr.xpath("./w:cols")[0].set(WNS_COLS_NUM, str(cols))
        
    section = document.add_section(WD_SECTION_START.NEW_PAGE)
    # col_nb is number of column layout
    set_number_of_columns(section, col_nb)
    

    Sau đó chúng ta thực hiện thêm đoạn văn giống như kiểu layout truyền thống. Đoạn văn sẽ được thêm theo thứ tự các cột, từ trái sang phải.

    p = document.add_paragraph(content)
    

    Ngoài ra, chúng ta cũng có thể thêm phần căn lề (trái, phải, giữa ) cho đoạn văn như sau:

    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    
    • Căn lề trái
     p.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
    
    • Căn lề phải
    p.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
    
    • Căn lề giữa
    p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    • Căn lề hai bên
    p.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
    

    4.3. Thêm câu cho đoạn văn

    Thư viện python-docx hỗ trợ chèn thêm câu riêng lẻ vào trong đoạn văn đã được khởi tạo:

    # initialize new paragraph
    p = document.add_paragraph(content)
    
    # add sentence to initialized paragraph
    sentence_element = p.add_run(str(content))
    

    4.3.1. Highlight background

    Bạn cũng có thể highlight background cho từng câu bằng các màu yêu thích như sau:(highlight là tên màu )

    from docx.enum.text import WD_COLOR_INDEX
    
    if highlight == 'black':
      color_element = WD_COLOR_INDEX.BLACK
    elif highlight == 'blue':
      color_element = WD_COLOR_INDEX.BLUE
    elif highlight == 'green':
      color_element = WD_COLOR_INDEX.BRIGHT_GREEN
    elif highlight == 'dark blue':
       color_element = WD_COLOR_INDEX.DARK_BLUE
    elif highlight == 'dark red':
      color_element = WD_COLOR_INDEX.DARK_RED
    elif highlight == 'dark yellow':
      color_element = WD_COLOR_INDEX.DARK_YELLOW
    elif highlight == 'dark green':
       color_element = WD_COLOR_INDEX.GREEN
    elif highlight == 'pink':
      color_element = WD_COLOR_INDEX.PINK
    elif highlight == 'red':
      color_element = WD_COLOR_INDEX.PINK
    elif highlight == 'white':
      color_element = WD_COLOR_INDEX.WHITE
    elif highlight == 'teal':
      color_element = WD_COLOR_INDEX.TEAL
    elif highlight == 'yellow':
      color_element = WD_COLOR_INDEX.YELLOW
    elif highlight == 'violet':
      color_element = WD_COLOR_INDEX.VIOLET
    elif highlight == 'gray25':
      color_element = WD_COLOR_INDEX.GRAY_25
    elif highlight == 'gray50':
      color_element = WD_COLOR_INDEX.GRAY_50
      
    style = document.styles.add_style("document style", WD_STYLE_TYPE.CHARACTER)
    style.font.highlight_color = color_element
    sentence_element = p.add_run(str(c), style=self.style)
    

    4.3.2. In đậm, nghiêng, gạch chân

    Bạn cũng có thể thêm highlight cho bằng thêm in đậm, in nghiêng hay gạch chân như khi người sử dụng trực tiếp trên file MS.

     # set bold, italic, underline value which is boolean value True or False
    sentence_element = p.add_run(str(content)
    sentence_element.bold = bold
    sentence_element.italic = italic
    entence_element.underline = underline
    

    5. Picture

    Bạn cũng có thể chèn ảnh trưc tiếp vào python-docx bằng đường dẫn tới file ảnh cần chèn hoặc ảnh đã được biểu diễn dạng ma trận. Bạn cũng có thể điều chỉnh kích thước ảnh phù hợp với văn bản của mình.

    import cv2
    from docx.shared import Inches
    from io import BytesIO
    import numpy as np
    
    
    def add_picture(document, image_path_or_stream, width):
         """Add picture to image"""
         if isinstance(image_path_or_stream, str):
             img = cv2.imread(image_path_or_stream)
         else:
             img = np.array(image_path_or_stream)
    
         is_success, im_buf_arr = cv2.imencode(".jpg", img)
         byte_im = im_buf_arr.tobytes()
         stream = BytesIO(byte_im)
         document.add_picture(stream, width=Inches(width))
         
    add_picture(document, 'example.jpg', 5.0)
    

    Lời kết

    Python-docx là một thư viện hỗ trợ mạnh mẽ về cách tạo lập hay sửa đổi văn bản docx. Tuy nhiên để có thể tận dụng hết các tính năng của Microsoft Word thì các bạn cần tìm hiểu sâu thêm các api của Mircosoft Word. Còn nếu bạn chỉ muốn sử dụng tính năng đơn giản thì python-docx vẫn là sự lựa chọn hết sức tuyệt vời. Cảm ơn các bạn đã theo dõi bài đọc của mình