I am trying to remove all the text from a word document and leave just the images.
I tried doing
for p in document.paragraphs:
p.text = ''
but that removes everything so then i set a condition like:
for p in document.paragraphs:
if len(p.text)>0:
p.text = ''
it worked but did not save the images within paragraphs that included text, and it came with its own set of problems like empty bullet points and lists, etc. final solution i came up to is
get all the paragraphs that have images using beautiful soup and then loop through the paragraphs using docx to remove those that dont have images. here is the problem, there are images that are inside paragraphs with words around them, I tried using beautiful soup to remove those texts like:
soup = BeautifulSoup(p._p.xml , 'xml')
for txt in soup.find_all('w:t'):
txt.string.replace_with("")
print(soup.prettify())
document.paragraphs[i] = soup.prettify()
print(document.paragraphs[i]._p.xml)
print(soup.prettify())
gives the xml tags without the text (good) print(document.paragraphs[i]._p.xml)
gives the xml tags without the text (good) now save the document and i still see the text so i print all the paragraphs using a loop and i get the xml tags with the text (bad)
what is the problem here? print(type(document.paragraphs))
gives <class 'list'>
so one would assume it works exactly like a normal list?
source https://stackoverflow.com/questions/77822620/how-to-replace-a-xml-tag-in-a-word-document-using-python-docx-and-bs4
Comments
Post a Comment