002-统计docx文件中()出现的次数

本文介绍了如何使用Python的python-docx库读取.docx文件,并通过正则表达式统计括号的数量及提取括号内的字母,示例代码展示了具体操作过程。
摘要由CSDN通过智能技术生成
  • 知识点:
    1、如何读取docx文件,pip install python-docx包,导包用from docx import Document
    2、将docx文件读取成字符串,进行正则匹配,即可统计
import re
from docx import Document

# 读取Word文档内容到一个字符串
def read_word_to_string(doc_path):
    doc = Document(doc_path)
    text = ''
    for paragraph in doc.paragraphs:
        text += paragraph.text + ' '  # 添加空格以确保连续段落间的内容也被正确匹配
    return text


# 使用正则表达式计算 () 出现的次数
def count_parentheses(text):
    pattern = r'\('  # 匹配左括号,右括号同理(注意这里只计算了左括号,需要同时考虑左右括号的情况)
    left_parentheses_count = len(re.findall(pattern, text))

    pattern = r'\)'
    right_parentheses_count = len(re.findall(pattern, text))

    # 如果左括号和右括号数量相等,则返回总的括号数,否则可能有未闭合的括号
    if left_parentheses_count == right_parentheses_count:
        return left_parentheses_count
    else:
        print("Warning: Unbalanced parentheses detected!")


def match_parentheses_content(text, limit=10):  # 默认只返回前10个括号中的内容
    pattern = r'\((.*?)\)'  # 匹配括号中的内容,非贪婪模式
    matches = re.findall(pattern, text)[:limit]  # 获取前limit个括号中的内容
    matched_letters = [re.sub(r'\W+', '', match) for match in matches]  # 去除每个匹配项中的非字母字符
    # 判断题目中括号内的字母,是否正确
    return matched_letters


doc_path = r"D:\test\book\test.docx"
word_content = read_word_to_string(doc_path)
word_content = word_content.replace('(', '(')
word_content = word_content.replace(')', ')')
word_content = word_content.upper()

print("括号出现的次数: ",  count_parentheses(word_content))
# 括号出现的次数:  11

print("括号里的字母: ",  match_parentheses_content(word_content,10)) # 只要前10个括号里的字母:  ['B', 'C', 'A', '_B', 'A', 'B', 'B', 'B', 'B', 'C']
  • 结果
  • 在这里插入图片描述
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昂立的狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值