小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python解析Word文檔的自動(dòng)編號(hào)

 小小明代碼實(shí)體 2024-06-19 發(fā)布于廣東

關(guān)于自動(dòng)編號(hào)的知識(shí)可以參考《在 Open XML WordprocessingML 中使用編號(hào)列表

鏈接:https://learn.microsoft.com/zh-cn/previous-versions/office/ee922775(v=office.14)

python-docx庫并不能直接解析出Word文檔的自動(dòng)編號(hào),因?yàn)樵磔^為復(fù)雜,但我們希望python能夠讀取自動(dòng)編號(hào)對應(yīng)的文本。

基本解析原理

為了測試驗(yàn)證,我們創(chuàng)建一個(gè)帶有編號(hào)的文檔進(jìn)行測試,例如:

image-20240612115513012

然后我們先看看主文檔中,對應(yīng)的xml存儲(chǔ):

from docx import Document

doc = Document(r"編號(hào)測試1.docx")
for paragraph in doc.paragraphs:
    print(paragraph._element.xml)
    break

結(jié)果:

<w:p ...>
  <w:pPr>
    <w:numPr>
      <w:ilvl w:val="0"/>
      <w:numId w:val="1"/>
    </w:numPr>
    <w:bidi w:val="0"/>
    <w:ind w:left="0" w:leftChars="0" w:firstLine="0" w:firstLineChars="0"/>
    <w:rPr>
      <w:rFonts w:hint="eastAsia"/>
      <w:lang w:val="en-US" w:eastAsia="zh-CN"/>
    </w:rPr>
  </w:pPr>
  <w:r>
    <w:rPr>
      <w:rFonts w:hint="eastAsia"/>
      <w:lang w:val="en-US" w:eastAsia="zh-CN"/>
    </w:rPr>
    <w:t>第一章</w:t>
  </w:r>
</w:p>

在微軟的文檔中,說明了最重要的部分:

w:numPr 元素包含自動(dòng)編號(hào)元素。w:ilvl 元素從零開始表示編號(hào)等級(jí),w:numId 元素是編號(hào)部件的索引。

w:numId 為 0 值時(shí) ,表示編號(hào)已經(jīng)被刪除段落不含列表項(xiàng)。

所以我們可以根據(jù)段落是否存在w:numPr并且w:numId的值不為0判斷段落是否存在自動(dòng)編號(hào)。

然后我們需要獲取每個(gè)w:numId對應(yīng)的自動(dòng)編號(hào)狀態(tài),這個(gè)信息存儲(chǔ)在zip壓縮包的\word\numbering.xml文件中,可以參考微軟文檔的示例:

image-20240612125602707

w:numbering同時(shí)包含w:numw:abstractNum兩種節(jié)點(diǎn),其中w:num記錄了 每個(gè)numId對應(yīng)的abstractNumId,而w:abstractNum記錄了每個(gè)abstractNumId對應(yīng)的編號(hào)格式,包含了每個(gè)級(jí)別的編號(hào)樣式信息。對于w:num,python-docx庫已經(jīng)幫我們解析好,可以直接讀取,但w:abstractNum節(jié)點(diǎn)python-docx庫卻并未進(jìn)行解析,只能我們自己進(jìn)行xml解析。

可以通過如下代碼獲取每個(gè)numId對應(yīng)的abstractNumId

from docx import Document

doc = Document(r"編號(hào)測試1.docx")
numbering_part = doc.part.numbering_part._element
numId2abstractId = {
    num.numId: num.abstractNumId.val for num in numbering_part.num_lst
}

接下來我們需要解析w:abstractNum節(jié)點(diǎn),查閱python-docx庫的源碼可以知道,它使用lxml的etree進(jìn)行xml解析。

初步解析代碼為:

from docx.oxml.ns import qn

abstractNumId2style = {}
for abstractNumIdTag in numbering_part.findall(qn("w:abstractNum")):
    abstractNumId = abstractNumIdTag.get(qn("w:abstractNumId"))
    for lvlTag in abstractNumIdTag.findall(qn("w:lvl")):
        ilvl = lvlTag.get(qn("w:ilvl"))
        style = {tag.tag[tag.tag.rfind("}") + 1:]: tag.get(qn("w:val"))
                 for tag in lvlTag.xpath("./*[@w:val]", namespaces=numbering_part.nsmap)}
        abstractNumId2style[(int(abstractNumId), int(ilvl))] = style
print(abstractNumId2style)

注意:docx.oxml.ns的qn函數(shù)可以將w:轉(zhuǎn)換為對應(yīng)的命名空間名稱,但對于xpath表達(dá)式卻無法正確處理,所以對于xpath表達(dá)式使用namespaces傳入對應(yīng)的命名空間。

除了上面的解析方法以外,還可以事先將節(jié)點(diǎn)的所有命名空間清除后再解析,清除代碼如下:

def remove_namespace(node):
 node_tag = node.tag
 if '}' in node_tag:
     node.tag = node_tag[node_tag.rfind("}") + 1:]
 for attr_key in list(node.attrib):
     if '}' in attr_key:
         new_attr_key = attr_key[attr_key.rfind("}") + 1:]
         node.attrib[new_attr_key] = node.attrib.pop(attr_key)
 for child in node:
     remove_namespace(child)
 return node

這樣可以遞歸消除目標(biāo)節(jié)點(diǎn)所有子節(jié)點(diǎn)的命名空間。

可以每個(gè)類別每個(gè)級(jí)別的自動(dòng)編號(hào)的屬性信息:

{(0, 0): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.', 'lvlJc': 'left'}, (0, 1): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.', 'lvlJc': 'left'}, (0, 2): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.', 'lvlJc': 'left'}, (0, 3): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.', 'lvlJc': 'left'}, (0, 4): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.%5.', 'lvlJc': 'left'}, (0, 5): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.%5.%6.', 'lvlJc': 'left'}, (0, 6): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.%5.%6.%7.', 'lvlJc': 'left'}, (0, 7): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.%5.%6.%7.%8.', 'lvlJc': 'left'}, (0, 8): {'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.%4.%5.%6.%7.%8.%9.', 'lvlJc': 'left'}}

當(dāng)然我們只測試了最基本的數(shù)值型自動(dòng)編號(hào),有些自動(dòng)編號(hào)對應(yīng)的節(jié)點(diǎn)沒有直接的w:numFmt節(jié)點(diǎn),解析代碼還需針對性調(diào)整。

微軟的文檔中提到,對多級(jí)列表的某一級(jí)列表進(jìn)行特殊設(shè)定時(shí),w:num內(nèi)會(huì)出現(xiàn)w:lvlOverride節(jié)點(diǎn),但本人使用wps反復(fù)測試過后并沒有出現(xiàn)。估計(jì)這種格式的xml只會(huì)在老版的office中出現(xiàn),而且我們也不會(huì)故意在多級(jí)列表的某一級(jí)進(jìn)行特殊設(shè)定,所以我們不考慮這種情況。

還需要考慮 w:suff 元素控制的列表后綴,即列表項(xiàng)與段落之間的空白內(nèi)容,有可能為制表符和空格,也可以什么都沒有。處理代碼為:

{"space": " ", "nothing": ""}.get(style.get("suff"), "\t")

多級(jí)編號(hào)處理

首先嘗試讀取每個(gè)段落對應(yīng)的自動(dòng)編號(hào)樣式:

for paragraph in doc.paragraphs:
    numpr = paragraph._element.pPr.numPr
    if numpr is not None and numpr.numId.val != 0:
        numId = numpr.numId.val
        ilvl = numpr.ilvl.val
        abstractId = numId2abstractId[numId]
        style = abstractNumId2style[(abstractId, ilvl)]
        print(style)
    print(paragraph.text)

結(jié)果:

{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.', 'lvlJc': 'left'}
第一章
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.', 'lvlJc': 'left'}
第一節(jié)
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.', 'lvlJc': 'left'}
第二節(jié)
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.', 'lvlJc': 'left'}
第一條
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.%3.', 'lvlJc': 'left'}
第二條
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.', 'lvlJc': 'left'}
第二章
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.', 'lvlJc': 'left'}
第三章

我們需要一個(gè)計(jì)數(shù)器來記錄每個(gè)樣式出現(xiàn)的次數(shù),從而生成其對應(yīng)的編號(hào)。

cache = {}
for paragraph in doc.paragraphs:
    numpr = paragraph._element.pPr.numPr
    lvlText = ""
    if numpr is not None and numpr.numId.val != 0:
        numId = numpr.numId.val
        ilvl = numpr.ilvl.val
        abstractId = numId2abstractId[numId]
        style = abstractNumId2style[(abstractId, ilvl)]
        if (abstractId, ilvl) in cache:
            cache[(abstractId, ilvl)] += 1
        else:
            cache[(abstractId, ilvl)] = int(style["start"])
        lvlText = style.get("lvlText")
        for i in range(0, ilvl + 1):
            lvlText = lvlText.replace(f'%{i + 1}', str(cache[(abstractId, i)]))
        suff_text = {"space": " ", "nothing": ""}.get(style.get("suff"), "\t")
        lvlText += suff_text
    print(lvlText + paragraph.text)

結(jié)果:

1.	第一章
1.1.	第一節(jié)
1.2.	第二節(jié)
1.2.1.	第一條
1.2.2.	第二條
2.	第二章
3.	第三章

各種其他類型的編號(hào)生成

為了盡量多的支持更多類型的編號(hào),我創(chuàng)建了如下測試文件:

image-20240612161333048

我們沒有必要獲取對應(yīng)的圓圈數(shù)字,圓圈就獲取對應(yīng)的整數(shù)。

除了三種日文編號(hào),上面的示例幾乎包含所有的編號(hào)類型。需要注意三位數(shù)以上的數(shù)字格式,其xml有些特殊,例如:

<w:lvl>
  <w:start w:val="1"/>
  <mc:AlternateContent>
    <mc:Choice Requires="w14">
      <w:numFmt w:val="custom" w:format="001, 002, 003, ..."/>
    </mc:Choice>
    <mc:Fallback>
      <w:numFmt w:val="decimal"/>
    </mc:Fallback>
  </mc:AlternateContent>
  <w:suff w:val="space"/>
  <w:lvlText w:val="%1"/>
  <w:lvlJc w:val="left"/>
  <w:pPr>
    <w:tabs>
      <w:tab w:val="left" w:pos="0"/>
    </w:tabs>
  </w:pPr>
  <w:rPr>
    <w:rFonts w:hint="default"/>
  </w:rPr>
</w:lvl>

基于此,解析格式的代碼也作出如下調(diào)整:

abstractNumId2style = {}
for abstractNumIdTag in numbering_part.findall(qn("w:abstractNum")):
    abstractNumId = abstractNumIdTag.get(qn("w:abstractNumId"))
    for lvlTag in abstractNumIdTag.findall(qn("w:lvl")):
        ilvl = lvlTag.get(qn("w:ilvl"))
        style = {tag.tag[tag.tag.rfind("}") + 1:]: tag.get(qn("w:val"))
                 for tag in lvlTag.xpath("./*[@w:val]", namespaces=numbering_part.nsmap)}
        if "numFmt" not in style:
            numFmtVal = lvlTag.xpath("./mc:AlternateContent/mc:Fallback/w:numFmt/@w:val",
                                     namespaces=numbering_part.nsmap)
            if numFmtVal and numFmtVal[0] == "decimal":
                numFmt_format = lvlTag.xpath("./mc:AlternateContent/mc:Choice/w:numFmt/@w:format",
                                             namespaces=numbering_part.nsmap)
                if numFmt_format:
                    style["numFmt"] = "decimal" + numFmt_format[0].split(",")[0]
        if style.get("numFmt") == "decimalZero":
            style["numFmt"] = "decimal01"
        abstractNumId2style[(int(abstractNumId), int(ilvl))] = style

目前只發(fā)現(xiàn)這種基于decimal的格式,所以只針對這種自定義格式處理,其他類型的統(tǒng)一認(rèn)為是沒有自動(dòng)編號(hào)。另外既然三位數(shù)的整數(shù)格式已經(jīng)被我們命名為decimal001,那么也將二位數(shù)的decimalZero修改為decimal01。

目前測試出這個(gè)文件有以下這些numFmt

bullet,cardinalText,chineseCounting,chineseLegalSimplified,decimal,decimalEnclosedCircleChinese,ideographTraditional,ideographZodiac,lowerLetter,lowerRoman,ordinal,ordinalText,upperLetter,upperRoman

下面我們預(yù)先選擇一些可能比較復(fù)雜的轉(zhuǎn)換編寫相應(yīng)的函數(shù):

正整數(shù)轉(zhuǎn)換為大寫字母

代碼如下:

def int2upperLetter(num):
    result = []
    while num > 0:
        num -= 1
        remainder = num % 26
        result.append(chr(remainder + ord('A')))
        num //= 26
    return "".join(reversed(result))

正整數(shù)轉(zhuǎn)換為羅馬數(shù)字

def int2upperRoman(num):
    t = [
        (1000, 'M'), (900, 'CM'), (500, 'D'),
        (400, 'CD'), (100, 'C'), (90, 'XC'),
        (50, 'L'), (40, 'XL'),  (10, 'X'),
        (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
    ]
    roman_num = ''
    i = 0
    while num > 0:
        val, syb = t[i]
        for _ in range(num // val):
            roman_num += syb
            num -= val
        i += 1
    return roman_num

正整數(shù)轉(zhuǎn)換為英文基數(shù)字

def int2cardinalText(num):
    if not isinstance(num, int) or num < 0 or num > 999999999999:
        raise ValueError(
            "Invalid number: must be a positive integer within four digits")
    base = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
            "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
            "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
    tens = ["", "", "Twenty", "Thirty", "Fourty",
            "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
    thousands = ["", "Thousand", "Million", "Billion"]

    def two_digits(n):
        if n < 20:
            return base[n]
        ten, unit = divmod(n, 10)
        if unit == 0:
            return f"{tens[ten]}"
        else:
            return f"{tens[ten]}-{base[unit]}"

    def three_digits(n):
        hundred, rest = divmod(n, 100)
        if hundred == 0:
            return two_digits(rest)
        result = f"{base[hundred]} hundred "
        if rest > 0:
            result += two_digits(rest)
        return result.strip()
    if num < 99:
        return two_digits(num)
    chunks = []
    while num > 0:
        num, remainder = divmod(num, 1000)
        chunks.append(remainder)
    words = []
    for i in range(len(chunks) - 1, -1, -1):
        if chunks[i] == 0:
            continue
        chunk_word = three_digits(chunks[i])
        if thousands[i]:
            chunk_word += f" {thousands[i]}"
        words.append(chunk_word)
    words = " ".join(words).lower()
    return words[0].upper()+words[1:]

正整數(shù)轉(zhuǎn)換為英文序數(shù)字

def int2ordinalText(num):
    if not isinstance(num, int) or num < 0 or num > 999999:
        raise ValueError(
            "Invalid number: must be a positive integer within four digits")
    base = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
            "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
            "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
    baseth = ['Zeroth', 'First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh',
              'Eighth', 'Ninth', 'Tenth', 'Eleventh', 'Twelfth', 'Thirteenth', 'Fourteenth',
              'Fifteenth', 'Sixteenth', 'Seventeenth', 'Eighteenth', 'Nineteenth', 'Twentieth']
    tens = ["", "", "Twenty", "Thirty", "Fourty",
            "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
    tensth = ["", "", "Twentieth", "Thirtieth", "Fortieth",
              "Fiftieth", "Sixtieth", "Seventieth", "Eightieth", "Ninetieth"]

    def two_digits(n):
        if n <= 20:
            return baseth[n]
        ten, unit = divmod(n, 10)
        result = tensth[ten]
        if unit != 0:
            result = f"{tens[ten]}-{baseth[unit]}"
        return result

    thousand, num = divmod(num, 1000)
    result = []
    if thousand > 0:
        if num == 0:
            return f"{int2cardinalText(thousand)} thousandth"
        result.append(f"{int2cardinalText(thousand)} thousand")
    hundred, num = divmod(num, 100)
    if hundred > 0:
        if num == 0:
            result.append(f"{base[hundred]} hundredth")
            return " ".join(result)
        result.append(f"{base[hundred]} hundred")
    result.append(two_digits(num))
    result = " ".join(result).lower()
    return result[0].upper() + result[1:]

會(huì)復(fù)用前面的基數(shù)字轉(zhuǎn)換規(guī)則。

正整數(shù)轉(zhuǎn)換為中文數(shù)字

import re


def int2Chinese(num, ch_num, units):
    if not (0 <= num <= 99999999):
        raise ValueError("僅支持小于一億以內(nèi)的正整數(shù)")

    def int2Chinese_in(num, ch_num, units):
        if not (0 <= num <= 9999):
            raise ValueError("僅支持小于一萬以內(nèi)的正整數(shù)")
        result = [ch_num[int(i)] + unit for i, unit in zip(reversed(str(num).zfill(4)), units)]
        result = "".join(reversed(result))
        zero_char = ch_num[0]
        result = re.sub(f"(?:{zero_char}[{units}])+", zero_char, result)
        result = result.rstrip(units[0])
        if result != zero_char:
            result = result.rstrip(zero_char)
        if result.lstrip(zero_char).startswith("一十"):
            result = result.replace("一", "")
        return result

    if num < 10000:
        result = int2Chinese_in(num, ch_num, units)
    else:
        left = num // 10000
        right = num % 10000
        result = int2Chinese_in(left, ch_num, units) + "萬" + int2Chinese_in(right, ch_num, units)
    if result != ch_num[0]:
        result = result.strip(ch_num[0])
    return result


def int2ChineseCounting(num):
    return int2Chinese(num, ch_num='〇一二三四五六七八九', units='個(gè)十百千')


def int2ChineseLegalSimplified(num):
    return int2Chinese(num, ch_num='零壹貳叁肆伍陸柒捌玖', units='個(gè)拾佰仟')

整體封裝并改進(jìn)

最終封裝成為一個(gè)類:

import re

from docx import Document
from docx.oxml.ns import qn


class WithNumberDocxReader:
    ideographTraditional = "甲乙丙丁戊己庚辛壬癸"
    ideographZodiac = "子丑寅卯辰巳午未申酉戌亥"

    def __init__(self, docx, gap_text="\t"):
        self.docx = Document(docx)
        self.numId2style = self.get_style_data()
        self.gap_text = gap_text
        self.cnt = {}
        self.cache = {}
        self.result = []

    @property
    def texts(self):
        if self.result:
            return self.result.copy()
        self.cnt.clear()
        self.cache.clear()
        for paragraph in self.docx.paragraphs:
            number_text = self.get_number_text(paragraph._element.pPr.numPr)
            self.result.append(number_text + paragraph.text)
        return self.result.copy()

    def get_style_data(self):
        numbering_part = self.docx.part.numbering_part._element
        abstractId2numId = {num.abstractNumId.val: num.numId for num in numbering_part.num_lst}
        numId2style = {}
        for abstractNumIdTag in numbering_part.findall(qn("w:abstractNum")):
            abstractNumId = abstractNumIdTag.get(qn("w:abstractNumId"))
            numId = abstractId2numId[int(abstractNumId)]
            for lvlTag in abstractNumIdTag.findall(qn("w:lvl")):
                ilvl = lvlTag.get(qn("w:ilvl"))
                style = {tag.tag[tag.tag.rfind("}") + 1:]: tag.get(qn("w:val"))
                         for tag in lvlTag.xpath("./*[@w:val]", namespaces=numbering_part.nsmap)}
                if "numFmt" not in style:
                    numFmtVal = lvlTag.xpath("./mc:AlternateContent/mc:Fallback/w:numFmt/@w:val",
                                             namespaces=numbering_part.nsmap)
                    if numFmtVal and numFmtVal[0] == "decimal":
                        numFmt_format = lvlTag.xpath("./mc:AlternateContent/mc:Choice/w:numFmt/@w:format",
                                                     namespaces=numbering_part.nsmap)
                        if numFmt_format:
                            style["numFmt"] = "decimal" + numFmt_format[0].split(",")[0]
                if style.get("numFmt") == "decimalZero":
                    style["numFmt"] = "decimal01"
                numId2style[(numId, int(ilvl))] = style
        return numId2style

    @staticmethod
    def int2upperLetter(num):
        result = []
        while num > 0:
            num -= 1
            remainder = num % 26
            result.append(chr(remainder + ord('A')))
            num //= 26
        return "".join(reversed(result))

    @staticmethod
    def int2upperRoman(num):
        t = [
            (1000, 'M'), (900, 'CM'), (500, 'D'),
            (400, 'CD'), (100, 'C'), (90, 'XC'),
            (50, 'L'), (40, 'XL'), (10, 'X'),
            (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
        ]
        roman_num = ''
        i = 0
        while num > 0:
            val, syb = t[i]
            for _ in range(num // val):
                roman_num += syb
                num -= val
            i += 1
        return roman_num

    @staticmethod
    def int2cardinalText(num):
        if not isinstance(num, int) or num < 0 or num > 999999999:
            raise ValueError(
                "Invalid number: must be a positive integer within four digits")
        base = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
                "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
                "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        tens = ["", "", "Twenty", "Thirty", "Fourty",
                "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        thousands = ["", "Thousand", "Million", "Billion"]

        def two_digits(n):
            if n < 20:
                return base[n]
            ten, unit = divmod(n, 10)
            if unit == 0:
                return f"{tens[ten]}"
            else:
                return f"{tens[ten]}-{base[unit]}"

        def three_digits(n):
            hundred, rest = divmod(n, 100)
            if hundred == 0:
                return two_digits(rest)
            result = f"{base[hundred]} hundred "
            if rest > 0:
                result += two_digits(rest)
            return result.strip()

        if num < 99:
            return two_digits(num)
        chunks = []
        while num > 0:
            num, remainder = divmod(num, 1000)
            chunks.append(remainder)
        words = []
        for i in range(len(chunks) - 1, -1, -1):
            if chunks[i] == 0:
                continue
            chunk_word = three_digits(chunks[i])
            if thousands[i]:
                chunk_word += f" {thousands[i]}"
            words.append(chunk_word)
        words = " ".join(words).lower()
        return words[0].upper() + words[1:]

    @staticmethod
    def int2ordinalText(num):
        if not isinstance(num, int) or num < 0 or num > 999999:
            raise ValueError(
                "Invalid number: must be a positive integer within four digits")
        base = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
                "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
                "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        baseth = ['Zeroth', 'First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh',
                  'Eighth', 'Ninth', 'Tenth', 'Eleventh', 'Twelfth', 'Thirteenth', 'Fourteenth',
                  'Fifteenth', 'Sixteenth', 'Seventeenth', 'Eighteenth', 'Nineteenth', 'Twentieth']
        tens = ["", "", "Twenty", "Thirty", "Fourty",
                "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        tensth = ["", "", "Twentieth", "Thirtieth", "Fortieth",
                  "Fiftieth", "Sixtieth", "Seventieth", "Eightieth", "Ninetieth"]

        def two_digits(n):
            if n <= 20:
                return baseth[n]
            ten, unit = divmod(n, 10)
            result = tensth[ten]
            if unit != 0:
                result = f"{tens[ten]}-{baseth[unit]}"
            return result

        thousand, num = divmod(num, 1000)
        result = []
        if thousand > 0:
            if num == 0:
                return f"{WithNumberDocxReader.int2cardinalText(thousand)} thousandth"
            result.append(f"{WithNumberDocxReader.int2cardinalText(thousand)} thousand")
        hundred, num = divmod(num, 100)
        if hundred > 0:
            if num == 0:
                result.append(f"{base[hundred]} hundredth")
                return " ".join(result)
            result.append(f"{base[hundred]} hundred")
        result.append(two_digits(num))
        result = " ".join(result).lower()
        return result[0].upper() + result[1:]

    @staticmethod
    def int2Chinese(num, ch_num, units):
        if not (0 <= num <= 99999999):
            raise ValueError("僅支持小于一億以內(nèi)的正整數(shù)")

        def int2Chinese_in(num, ch_num, units):
            if not (0 <= num <= 9999):
                raise ValueError("僅支持小于一萬以內(nèi)的正整數(shù)")
            result = [ch_num[int(i)] + unit for i, unit in zip(reversed(str(num).zfill(4)), units)]
            result = "".join(reversed(result))
            zero_char = ch_num[0]
            result = re.sub(f"(?:{zero_char}[{units}])+", zero_char, result)
            result = result.rstrip(units[0])
            if result != zero_char:
                result = result.rstrip(zero_char)
            if result.lstrip(zero_char).startswith("一十"):
                result = result.replace("一", "")
            return result

        if num < 10000:
            result = int2Chinese_in(num, ch_num, units)
        else:
            left = num // 10000
            right = num % 10000
            result = int2Chinese_in(left, ch_num, units) + "萬" + int2Chinese_in(right, ch_num, units)
        if result != ch_num[0]:
            result = result.strip(ch_num[0])
        return result

    @staticmethod
    def int2ChineseCounting(num):
        return WithNumberDocxReader.int2Chinese(num, ch_num='〇一二三四五六七八九', units='個(gè)十百千')

    @staticmethod
    def int2ChineseLegalSimplified(num):
        return WithNumberDocxReader.int2Chinese(num, ch_num='零壹貳叁肆伍陸柒捌玖', units='個(gè)拾佰仟')

    def get_number_text(self, numpr):
        if numpr is None or numpr.numId.val == 0:
            return ""
        numId = numpr.numId.val
        ilvl = numpr.ilvl.val
        style = self.numId2style[(numId, ilvl)]
        numFmt: str = style.get("numFmt")
        lvlText = style.get("lvlText")
        if (numId, ilvl) in self.cnt:
            self.cnt[(numId, ilvl)] += 1
        else:
            self.cnt[(numId, ilvl)] = int(style["start"])
        pos = self.cnt[(numId, ilvl)]
        num_text = str(pos)
        if numFmt.startswith('decimal'):
            num_text = num_text.zfill(numFmt.count("0") + 1)
        elif numFmt == 'upperRoman':
            num_text = self.int2upperRoman(pos)
        elif numFmt == 'lowerRoman':
            num_text = self.int2upperRoman(pos).lower()
        elif numFmt == 'upperLetter':
            num_text = self.int2upperLetter(pos)
        elif numFmt == 'lowerLetter':
            num_text = self.int2upperLetter(pos).lower()
        elif numFmt == 'ordinal':
            num_text = f"{pos}{'th' if 11 <= pos <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(pos % 10, 'th')}"
        elif numFmt == 'cardinalText':
            num_text = self.int2cardinalText(pos)
        elif numFmt == 'ordinalText':
            num_text = self.int2ordinalText(pos)
        elif numFmt == 'ideographTraditional':
            if 1 <= pos <= 10:
                num_text = self.ideographTraditional[pos - 1]
        elif numFmt == 'ideographZodiac':
            if 1 <= pos <= 12:
                num_text = self.ideographZodiac[pos - 1]
        elif numFmt == 'chineseCounting':
            num_text = self.int2ChineseCounting(pos)
        elif numFmt == 'chineseLegalSimplified':
            num_text = self.int2ChineseLegalSimplified(pos)
        elif numFmt == 'decimalEnclosedCircleChinese':
            pass
        self.cache[(numId, ilvl)] = num_text
        for i in range(0, ilvl + 1):
            lvlText = lvlText.replace(f'%{i + 1}', self.cache.get((numId, i), ""))
        suff_text = {"space": " ", "nothing": ""}.get(style.get("suff"), self.gap_text)
        lvlText += suff_text
        return lvlText

調(diào)用測試:

if __name__ == '__main__':
    doc = WithNumberDocxReader(r"編號(hào)測試2.docx", "")
    for text in doc.texts:
        print(text)

順利達(dá)到打印出對應(yīng)的字符:

?點(diǎn)符
1.十進(jìn)制數(shù)
01.零加十進(jìn)制數(shù)
001 零零加十進(jìn)制數(shù)
0001 零零零加十進(jìn)制數(shù)
I 大寫羅馬數(shù)字 (I)
II 大寫羅馬數(shù)字 (II)
i 小寫羅馬數(shù)字
A.大寫字母A
a 小寫字母 (a)
0th 序數(shù) (1st, 2nd, 3rd)
Twelve 基數(shù)字 (One, Two Three)
First 序數(shù)字 (First, Second, Third)

癸 甲乙丙丁戊己庚辛壬癸
壹 中文大寫數(shù)字
10 圓圈數(shù)字
子 子丑寅卯辰巳午未申酉戌亥

第一章 中文數(shù)字

    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請遵守用戶 評(píng)論公約

    類似文章 更多