【发布时间】:2021-10-03 11:16:20
【问题描述】:
我正在尝试使用正则表达式语句来提取两个已知短语之间的特定文本块,这些短语将在其他文档中重复,并删除其他所有内容。然后将这几句话传递给其他函数。
我的问题似乎是,当我使用在同一行上搜索单词的正则表达式语句时,它可以工作。如果他们在不同的线路上,我会得到:
print(match.group(1).strip())
AttributeError: 'NoneType' object has no attribute 'group'
我希望未来的报告会根据之前编写的内容在不同的点有换行符 - 有没有办法通过删除所有换行符来首先准备文本,或者让我的正则表达式语句在搜索时忽略那些?
任何帮助都会很棒,谢谢!
import fitz
import re
doc = fitz.open(r'file.pdf')
text_list = [ ]
for page in doc:
text_list.append(page.getText())
#print(text_list[-1])
text_string = ' '.join(text_list)
test_string = "Observations of Client Behavior: THIS IS THE DESIRED TEXT. Observations of Client's response to skill acquisition" #works for this test
pat = r".*?Observations of Client Behavior: (.*) Observations of Client's response to skill acquisition*"
match = re.search(pat, text_string)
print(match.group(1).strip())
当我在长文本文件中搜索位于同一行的短语时,它可以工作。但是一旦它们在不同的线路上,它就不再起作用了。
这是给我一个问题的输入文本示例:
Observations of Client Behavior: Overall interfering behavior data trends are as followed: Aggression frequency
has been low and stable at 0 occurrences for the past two consecutive sessions. Elopement frequency is on an
overall decreasing trend. Property destruction frequency is on an overall decreasing trend. Non-compliance
frequency has been stagnant at 2 occurrences for the past two consecutive sessions, but overall on a
decreasing trend. Tantrum duration data are variable; data were at 89 minutes on 9/27/21, but have starkly
decreased to 0 minutes for the past two consecutive sessions. Observations of Client's response to skill
acquisition: Overall skill acquisition data trends are as followed: Frequency of excessive mands
【问题讨论】:
-
在代码中,“这是所需的文本”之后有“客户对技能获取的反应的观察”文本。所以你的模式可以匹配这个但是在你的示例输入中你没有在“攻击频率”之后“观察客户对技能获取的反应”,这是错误的原因。你也可以测试你的正则表达式here
-
@Alireza 这是我的复制/粘贴错误,抱歉!我编辑了代码以准确反映我所拥有的
-
@Alireza 在这里 - 当我在测试用例中插入换行符时,它不再起作用 regex101.com/r/EDb77r/1
-
您到底想从这个输入中得到什么? “观察客户行为:”之后的文字?
-
@alizera 是的。在那之后和关于技能获取的字符串之前。中间应该有3-4个句子取出来