我在一个目录中有.docx文件,我想得到两段之间的所有文本
示例:
Foo :
The foo is not easy, but we have to do it. We are looking for new things in our ad libitum way of life.
Bar :
我想得到:
The foo is not easy, but we have to do it.
We are looking for new things in our ad libitum way of life.
我写了这段代码:
import docx
import pathlib
import glob
import re
def rf(f1):
reader = docx.Document(f1)
alltext = []
for p in reader.paragraphs:
alltext.append(p.text)
return '\n'.join(alltext)
for f in docxfiles:
try:
fulltext = rf(f)
testf = re.findall(r'Foo\s*:(.*)\s*Bar', fulltext, re.DOTALL)
print(testf)
except IOError:
print('Error opening',f)
它返回None
我做错了什么
如果循环所有段落并打印段落文本,则文档文本将保持原样,但循环的单个
p.text
不包含完整的文档文本它与字符串一起工作:
输出:
如果你使用
你知道为什么你的正则表达式不匹配了。您的正则表达式可以处理整个文档文本
请参阅How to extract text from an existing docx file using python-docx如何获取整个文档文本
您还可以查找与
r'Foo\s*:'
匹配的段落,然后将下面所有段落.文本放入列表,直到找到与r'\s*Bar'
匹配的段落相关问题 更多 >
编程相关推荐