天天看點

盤點一個Python自動化辦公的實戰案例(word檔案處理)

大家好,我是Python進階者。

一、前言

前幾天在Python鉑金交流群【Jethro Shen】問了一個Python自動化辦公的問題,提問截圖如下:

盤點一個Python自動化辦公的實戰案例(word檔案處理)

代碼運作後的結果:

盤點一個Python自動化辦公的實戰案例(word檔案處理)

他預期的效果是選項和答案部分也需要顯示出來,目前看上去還是沒有顯示出來。

盤點一個Python自動化辦公的實戰案例(word檔案處理)

他的原始代碼如下:

import re

black_char = re.compile("[\s\u3000\xa0]+")

chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
title_rule = re.compile("\d+.")
option_rule = re.compile("\([ABCDEF]\)")
option_rule_search = re.compile("\([ABCDEF]\)[^(]+")
answer_rule = re.compile("\([ABCDEF]\)")

# 從word文檔的“一、單項選擇題”開始周遊資料
for paragraph in doc.paragraphs[1:100]:
    #  去除空白字元,将全角字元轉半角字元,并給括号之間調整為中間二個空格
    line = black_char.sub("", paragraph.text).replace(
        "(", "(").replace(")", ")").replace(".", ".").replace("()", "(  )").replace("【", "").replace("】", "")
    # 對于空白行就直接跳過
    if not line:
        continue
    if title_rule.search(line):
        print("題目", line)
    elif option_rule.search(line):
        print("選項", option_rule_search.findall(line))
    elif answer_rule.search(line):
        print("答案",answer_rule.findall(line))
    else:
        chinese_nums_match = chinese_nums_rule.search(line)
        if chinese_nums_match:
            print("題目", chinese_nums_match.group(1))
      

二、實作過程

這裡【瑜亮老師】指出是正規表達式的問題,沒比對到,自然就出不來結果。後來【不上班能幹啥!】給了一份代碼,如下所示:

import re

black_char = re.compile("[\s\u3000\xa0]+")

chinese_nums_rule = re.compile("[一二三四]、(.+?)\(")
title_rule = re.compile("\d+.")
option_rule = re.compile("([A-F]\..+?)\s")
# option_rule_search = re.compile("\([A-F]\)[^(]+")
answer_rule = re.compile("【答案】([A-F])")

# 從word文檔的“一、單項選擇題”開始周遊資料
for paragraph in doc.paragraphs[1:100]:
    #  去除空白字元,将全角字元轉半角字元,并給括号之間調整為中間二個空格
    line = black_char.sub(" ", paragraph.text).replace(
        "(", "(").replace(")", ")").replace(".", ".").replace("()", "(  )") + " "
    # 對于空白行就直接跳過
    if not line:
        continue
    if title_rule.match(line):
        print("題目", line)
    elif option_rule.match(line):
        print("選項", option_rule.findall(line))
        if '【答案】' in line and answer_rule.search(line):
            print("答案",answer_rule.findall(line))
    elif answer_rule.match(line):
        print("答案",answer_rule.findall(line))
    else:
        chinese_nums_match = chinese_nums_rule.match(line)
        if chinese_nums_match:
            print("題目", chinese_nums_match.group(1))
      

運作之後,可以得到預期發效果:

盤點一個Python自動化辦公的實戰案例(word檔案處理)

歸根結底,還是正規表達式的問題。

後來【甯同學】使用 openpyxl庫,也給了一份代碼,如下所示:

from docx import Document
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
ws.append(['題目','選項1','選項2','選項3','選項4','答案'])
doc = Document("題庫.docx")
all_runs = doc.paragraphs 
rows = []
for run in all_runs[1:]:
    print([run.text])
    if '【答案】' in run.text:
        text_list= run.text.replace('\n    ','\t\t').replace('【答案】','').split('\t\t')
        rows += text_list 
        ws.append(rows)
        rows = []
        continue
    text_list= run.text.replace('\n    ','\t\t').split('\t\t')
    rows += text_list 
wb.save('1.xlsx')
      

可以得到預期的效果,如下圖所示:

盤點一個Python自動化辦公的實戰案例(word檔案處理)

效果還是不錯的!

盤點一個Python自動化辦公的實戰案例(word檔案處理)

後來【不上班能幹啥!】還結合Pandas給了一份代碼,如下所示:

import re
import pandas as pd
from docx import Document

doc = Document("題庫.docx")
text = re.sub(r'<.*?>', '', doc.part.blob.decode('utf-8'), flags=re.S)

a = pd.DataFrame(re.findall(r'(\d+\..*?)(A\..*?)(B\..*?)(C\..*?)(D\..*?)【答案】([A-Z])', text), 
                 columns=['題目', '選項一', '選項二', '選項三', '選項四', '答案'])
a.replace([r'^\s+', '\s+$'], '', regex=True, inplace=True)
a.to_excel('題庫.xlsx', index=False)
      

這個Pandas功力已經到爐火純青的地步了!

盤點一個Python自動化辦公的實戰案例(word檔案處理)

三、總結

大家好,我是皮皮。這篇文章主要盤點了一個Python自動化辦公的問題,文中針對該問題,給出了具體的解析和代碼實作,幫助粉絲順利解決了問題。

繼續閱讀