Here batch processing of word documents is mainly through the python-docx non-standard library to achieve, by locating the document object, and then to the paragraph, and finally to a line of text so as to complete the processing for the text object.
Install python-docx using pip.
pip install python-docx
Importing the modules needed for the realization process
from docx import Document # Document Processing Objects from import RGBColor, Pt, Cm # Text Styling import os # Applications/documentation import glob # Document processing
Define the path of the file to be processed and the path of the generated target file.
source_file = 'C:/source' # Source file path target_file = 'C:/target' # Path to target file
will need to batch process the style of word documents into the source directory below, I have prepared a document here as a demonstration of processing.
Here is the part of the code block implementation that handles text styles.
for current_file in (source_file + '/*.docx'): # Iterate over word document files word_obj = Document(current_file) # Initialize the word object for para in word_obj.paragraphs: # Iterate over the current document paragraph for run in : # Iterate over the text block of the current paragraph if 'Python' in : # Determine if the current text block contains a Python string = True # Underlined = RGBColor(255, 0, 0) # Set the font color to red word_obj.save(target_file + '/' + (current_file))
The effect of the finished processing is as follows:
After the implementation of the above code block will be able to achieve the effect we want: batch set word document style.
Finally, to add a few more ways to use the tool, you can refer to the color comparison table below when setting the font color.
Color Comparison Table Address
For other font style settings refer to the following code block
''' # Bolded = True # Italics = True # Underline = True # Delete line = True # Font size = Pt(20) # Shadows = True '''
To use it, just call it directly in the text block. In the text processing above we are using the underline setting.
= True # Underlined
For example, if you need to add a shadow, you can do so directly in the current corresponding text block.
= True
Finally, one thing to note is that in the implementation of the processing of word documents do not use wps or other tools to open, otherwise there will be an error message can not find the file.
This article on Python Word document styles batch processing is introduced to this article, more related Python Word styles processing content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!