【问题标题】:How to remove special character when writing to docx?写入docx时如何删除特殊字符?
【发布时间】:2021-11-06 22:41:35
【问题描述】:

我正在寻找一些关于删除特殊字符的建议。 解释发生了什么。我正在向 docx 编写 mongo-query,但在写入 word 文档时删除特殊字符时遇到了一些麻烦。我是 python 新手,但如果有任何关于如何实现这一点的建议,我将不胜感激。

document = Document()

special_char='_!#$%^&*()<>?/\|}{~:;[]'

document.add_heading('This is a document',0)
for i in queryOutput: #imported Mongo Query 
    for y in special_char:
        p=document.add_paragraph(str(i).replace(y,"")) 
       
    
document.save('output.docx')

【问题讨论】:

    标签: python pymongo docx


    【解决方案1】:

    您可以使用正则表达式模式替换多个特殊字符。 Piotr 的回答给出了一些基本的想法,但他没有提到某些特殊字符具有特殊含义。所以在使用前应该将它们转义如下:

    import re
    document = Document()
    
    special_characters = "_!#$%^&*\(\)<>?\/\\\\|\}\{~:;\[\]"
    pattern = "[" + special_characters + "]"
    document.add_heading('This is a document',0)
    for i in queryOutput: #imported Mongo Query 
        cleaned_p = re.sub(pattern, "", str(i))
        p=document.add_paragraph(cleaned_p)         
    document.save('output.docx')
    

    【讨论】:

      【解决方案2】:
      import re
      
      for paragraph in queryOutput:
          sanitized_paragraph = re.sub("|".join(special_char), "", paragraph)
          p = document.add_paragraph(sanitized_paragraph)
      

      【讨论】:

        猜你喜欢
        • 2019-05-12
        • 2010-10-14
        • 2022-08-03
        • 1970-01-01
        • 2011-10-10
        • 2013-12-11
        • 1970-01-01
        • 2014-05-14
        • 1970-01-01
        相关资源
        最近更新 更多