Python解析Word文档的自动编号

news2024/10/5 18:34:17

关于自动编号的知识可以参考《在 Open XML WordprocessingML 中使用编号列表》

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

python-docx库并不能直接解析出Word文档的自动编号,因为原理较为复杂,但我们希望python能够读取自动编号对应的文本。

基本解析原理

为了测试验证,我们创建一个带有编号的文档进行测试,例如:

image-20240612115513012

然后我们先看看主文档中,对应的xml存储:

from docx import Document

doc = Document(r"编号测试1.docx")
for paragraph in doc.paragraphs:
    print(paragraph._element.xml)
    break

结果:

<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 元素包含自动编号元素。w:ilvl 元素从零开始表示编号等级,w:numId 元素是编号部件的索引。

w:numId 为 0 值时 ,表示编号已经被删除段落不含列表项。

所以我们可以根据段落是否存在w:numPr并且w:numId的值不为0判断段落是否存在自动编号。

然后我们需要获取每个w:numId对应的自动编号状态,这个信息存储在zip压缩包的\word\numbering.xml文件中,可以参考微软文档的示例:

image-20240612125602707

w:numbering同时包含w:numw:abstractNum两种节点,其中w:num记录了 每个numId对应的abstractNumId,而w:abstractNum记录了每个abstractNumId对应的编号格式,包含了每个级别的编号样式信息。对于w:num,python-docx库已经帮我们解析好,可以直接读取,但w:abstractNum节点python-docx库却并未进行解析,只能我们自己进行xml解析。

可以通过如下代码获取每个numId对应的abstractNumId

from docx import Document

doc = Document(r"编号测试1.docx")
numbering_part = doc.part.numbering_part._element
numId2abstractId = {
    num.numId: num.abstractNumId.val for num in numbering_part.num_lst
}

接下来我们需要解析w:abstractNum节点,查阅python-docx库的源码可以知道,它使用lxml的etree进行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函数可以将w:转换为对应的命名空间名称,但对于xpath表达式却无法正确处理,所以对于xpath表达式使用namespaces传入对应的命名空间。

除了上面的解析方法以外,还可以事先将节点的所有命名空间清除后再解析,清除代码如下:

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

这样可以递归消除目标节点所有子节点的命名空间。

可以每个类别每个级别的自动编号的属性信息:

{(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'}}

当然我们只测试了最基本的数值型自动编号,有些自动编号对应的节点没有直接的w:numFmt节点,解析代码还需针对性调整。

微软的文档中提到,对多级列表的某一级列表进行特殊设定时,w:num内会出现w:lvlOverride节点,但本人使用wps反复测试过后并没有出现。估计这种格式的xml只会在老版的office中出现,而且我们也不会故意在多级列表的某一级进行特殊设定,所以我们不考虑这种情况。

还需要考虑 w:suff 元素控制的列表后缀,即列表项与段落之间的空白内容,有可能为制表符和空格,也可以什么都没有。处理代码为:

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

多级编号处理

首先尝试读取每个段落对应的自动编号样式:

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)

结果:

{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.', 'lvlJc': 'left'}
第一章
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.', 'lvlJc': 'left'}
第一节
{'start': '1', 'numFmt': 'decimal', 'lvlText': '%1.%2.', 'lvlJc': 'left'}
第二节
{'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'}
第三章

我们需要一个计数器来记录每个样式出现的次数,从而生成其对应的编号。

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)

结果:

1.	第一章
1.1.	第一节
1.2.	第二节
1.2.1.	第一条
1.2.2.	第二条
2.	第二章
3.	第三章

各种其他类型的编号生成

为了尽量多的支持更多类型的编号,我创建了如下测试文件:

image-20240612161333048

我们没有必要获取对应的圆圈数字,圆圈就获取对应的整数。

除了三种日文编号,上面的示例几乎包含所有的编号类型。需要注意三位数以上的数字格式,其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>

基于此,解析格式的代码也作出如下调整:

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

目前只发现这种基于decimal的格式,所以只针对这种自定义格式处理,其他类型的统一认为是没有自动编号。另外既然三位数的整数格式已经被我们命名为decimal001,那么也将二位数的decimalZero修改为decimal01

目前测试出这个文件有以下这些numFmt

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

下面我们预先选择一些可能比较复杂的转换编写相应的函数:

正整数转换为大写字母

代码如下:

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

正整数转换为罗马数字

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

正整数转换为英文基数字

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:]

正整数转换为英文序数字

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:]

会复用前面的基数字转换规则。

正整数转换为中文数字

import re


def int2Chinese(num, ch_num, units):
    if not (0 <= num <= 99999999):
        raise ValueError("仅支持小于一亿以内的正整数")

    def int2Chinese_in(num, ch_num, units):
        if not (0 <= num <= 9999):
            raise ValueError("仅支持小于一万以内的正整数")
        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='个十百千')


def int2ChineseLegalSimplified(num):
    return int2Chinese(num, ch_num='零壹贰叁肆伍陆柒捌玖', units='个拾佰仟')

整体封装并改进

最终封装成为一个类:

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("仅支持小于一亿以内的正整数")

        def int2Chinese_in(num, ch_num, units):
            if not (0 <= num <= 9999):
                raise ValueError("仅支持小于一万以内的正整数")
            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='个十百千')

    @staticmethod
    def int2ChineseLegalSimplified(num):
        return WithNumberDocxReader.int2Chinese(num, ch_num='零壹贰叁肆伍陆柒捌玖', units='个拾佰仟')

    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

调用测试:

if __name__ == '__main__':
    doc = WithNumberDocxReader(r"编号测试2.docx", "")
    for text in doc.texts:
        print(text)

顺利达到打印出对应的字符:

点符
1.十进制数
01.零加十进制数
001 零零加十进制数
0001 零零零加十进制数
I 大写罗马数字 (I)
II 大写罗马数字 (II)
i 小写罗马数字
A.大写字母A
a 小写字母 (a)
0th 序数 (1st, 2nd, 3rd)
Twelve 基数字 (One, Two Three)
First 序数字 (First, Second, Third)

癸 甲乙丙丁戊己庚辛壬癸
壹 中文大写数字
10 圆圈数字
子 子丑寅卯辰巳午未申酉戌亥

第一章 中文数字

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1816428.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

0502 构成分析设计MOS管放大电路与FET异同点

构成&分析&设计MOS管放大电路&与FET有何异同点 MOSFET需具备什么样的条件才能正常放大信号&#xff1f;如何构成MOSFET放大电路如何分析和设计MOSFET放大电路1.图解分析 2.直流偏置及静态工作点的计算![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/fc…

6.7.31 使用端到端训练的基于 EfficientNet 的卷积网络在双视图乳房 X 线摄影中进行乳腺癌诊断

最好的技术之一进行了两次迁移学习:第一种是使用在自然图像上训练的模型来创建“块分类器”,对子图像进行分类;第二种是使用块分类器扫描整个乳房 X 光检查并创建“单视图全图像分类器”。建议进行第三次迁移学习,以获得一个“双视图分类器”,以使用两个乳房 X 光检查视图…

每日复盘-202406012

今日关注&#xff1a; 这几天市场打板情绪环境转好&#xff0c;轻仓试错 20240612 六日涨幅最大: ------1--------605258--------- 协和电子 五日涨幅最大: ------1--------605258--------- 协和电子 四日涨幅最大: ------1--------301036--------- 双乐股份 三日涨幅最大: --…

《亿级流量网站架构核心技术》-高可用-限流详解

背景 项目中遇到一个场景&#xff0c;用户点击按钮给缺勤员工发送扣薪通知。按照需求是一个月只会发送一次通知&#xff0c;在代码逻辑中已经做了兜底策略--在发送邮件之前先判断本月通知是否已发送&#xff0c;发送完之后将发送状态进行持久化。发邮件的时间大概在1分钟之内。…

看了这面经,测开上岸不远了

前段时间和4位来自百度、美团、快手、滴滴的高级测开大厂学长学姐&#xff0c;进行了一场直播&#xff0c;负责解答24届春招补录&25届找实习同学的问题 当天直播时长达2个小时&#xff0c;对于如何找测开实习&#xff0c;需要怎么准备项目&#xff0c;简历怎么写&#xff…

每天五分钟计算机视觉:如何在现有经典的卷积神经网络上进行微调

本文重点 在深度学习领域,卷积神经网络(Convolutional Neural Networks,CNN)因其强大的特征提取和分类能力而广泛应用于图像识别、自然语言处理等多个领域。然而,从头开始训练一个CNN模型往往需要大量的数据和计算资源,且训练时间较长。幸运的是,迁移学习(Transfer Le…

MySQL系列-语法说明以及基本操作(二)

1、MySQL数据表的约束 1.1、MySQL主键 “主键&#xff08;PRIMARY KEY&#xff09;”的完整称呼是“主键约束”。 MySQL 主键约束是一个列或者列的组合&#xff0c;其值能唯一地标识表中的每一行。这样的一列或多列称为表的主键&#xff0c;通过它可以强制表的实体完整性。 …

C++的爬山算法

爬山算法&#xff08;Hill Climbing Algorithm&#xff09;是一种局部搜索算法&#xff0c;它通过迭代搜索的方式寻找问题的局部最优解。在爬山过程中&#xff0c;算法总是选择当前状态邻域中最好&#xff08;即函数值最大或最小&#xff09;的状态作为下一个状态&#xff0c;直…

小程序 js+Canvas 绘制半圆环虚线进度条

效果图&#xff1a; 思路&#xff1a;过程分为三步&#xff0c;第1步&#xff0c;先画虚线底部背景&#xff0c;第2步&#xff0c;画动态的虚线&#xff08;已选虚线蓝颜色&#xff09;&#xff0c;第3步&#xff0c;画动态的外标&#xff08;已选虚线外位置的标&#xff09;&a…

AOSP12隐藏首页搜索框----隐藏google 搜索栏

目录 第一步&#xff1a;修改文件 第二步&#xff1a;修改文件 第三步&#xff1a;重新编译源码&#xff0c;启动模拟器 第四步、运行效果 第一步&#xff1a;修改文件 源码文件路径: packages/apps/Launcher3/res/layout/search_container_workspace.xml&#xff0c;将…

Navicat for MySQL 11软件下载附加详细安装教程

根据使用者情况表明Navicat Premium 能使你快速地在各种数据库系统间传输数据&#xff0c;或传输到一份指定 SQL 格式和编码的纯文本文件&#xff0c;计划不同数据库的批处理作业并在指定的时间运行&#xff0c;其他功能包括导入向导、导出向导、查询创建工具、报表创建工具、数…

【6】第一个Java程序:Hello World

一、引言 Java&#xff0c;作为一种广泛使用的编程语言&#xff0c;其强大的跨平台能力和丰富的库函数使其成为开发者的首选。对于初学者来说&#xff0c;编写并运行第一个Java程序是一个令人兴奋的时刻。本文将指导你使用Eclipse这一流行的集成开发环境&#xff08;IDE&#…

【对抗样本】【FGSM】Explaining and Harnessing Adversarial Examples 代码复现

简介 参考Pytorch官方的代码Adversarial Example Generation 参数设置(main.py) # 模型选择&#xff1a;GPU device mps if torch.backends.mps.is_available() else cpu # 数据集位置 dataset_path ../../../Datasets batch_size 1 shuffle True download False # 学习率…

express入门03增删改查

目录 1 搭建服务器2 静态文件托管3 引入bootstrap4 引入jquery5 编写后端接口5.1 添加列表查询方法5.2 添加路由5.3 添加数据表格 总结 我们前两篇介绍了如何利用express搭建服务器&#xff0c;如何实现静态资源托管。那利用这两篇的知识点&#xff0c;我们就可以实现一个小功能…

WebSocket 快速入门 与 应用

WebSocket 是一种在 Web 应用程序中实现实时、双向通信的技术。它允许客户端和服务器之间建立持久性的连接&#xff0c;以便可以在两者之间双向传输数据。 以下是 WebSocket 的一些关键特点和工作原理&#xff1a; 0.特点&#xff1a; 双向通信&#xff1a;WebSocket 允许服务…

艾宾浩斯winform单词系统+mysql

为用户提供集词典、题库、记忆单词功能于一体的应用&#xff0c;为用户提供目的性强、科学高效、多样化的记忆单词方法&#xff0c;使用户学习英语和记忆单词的效率得到提高 单词记忆模块 管理模块 查询单词 阅读英文 查看词汇 记忆单词 收藏单词 字段管理设置 统计 艾宾浩斯wi…

springBoot多数据源使用、配置

又参加了一个新的项目&#xff0c;虽然是去年做的项目&#xff0c;拿来复用改造&#xff0c;但是也学到了很多。这个项目会用到其他项目的数据&#xff0c;如果调用他们的接口取数据&#xff0c;我还是觉得太麻烦了。打算直接配置多数据源。 然后去另一个数据库系统中取出数据…

【C语音 || 数据结构】二叉树--堆

文章目录 前言堆1.1 二叉树的概念1.2 满二叉树和完美二叉树1.3 堆的概念1.4 堆的性质1.4 堆的实现1.4.1堆的向上调整算法1.4.1堆的向下调整算法1.4.1堆的接口实现1.4.1.1堆的初始化1.4.1.2堆的销毁1.4.1.3堆的插入1.4.1.4堆的删除1.4.1.4堆的判空1.4.1.4 获取堆的数据个数 前言…

当客户一上来就问你产品价格,你可以多尝试问问

做外贸业务&#xff0c;每个对产品不了解的客户&#xff0c;很多人一上来都会习惯性地问我们价格。一些新手业务会比较直接&#xff0c;一下子就把价格报出去了&#xff0c;很容易因为报错价格导致客户杳无音讯。 其实这个时候&#xff0c;我们最应该做的是尝试跟客户多聊一聊…

vuInhub靶场实战系列--Kioptrix Level #4

免责声明 本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关。 目录 免责声明前言一、环境配置1.1 靶场信息1.2 靶场配置 二、信息收集2.1 主机发现2.1.1 netdiscover2.1.2 arp-scan主机扫描 2.2 端口扫描2.3 指纹识别2.4 目…