Python在两个标记之间查找字符串

2024-04-29 09:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取存储在一个文件中的两个标记之间的内容,内容可能跨越多行。标记在文件中可以出现0次或1次。在

例如:文件内容可以是

title:Corruption Today: Corruption today in
content:Corruption Today: 
Corruption today in 
score:0.91750675

所以,在阅读“内容:”时,我的查询结果应该是“今日腐败:今日腐败”。 经过一些谷歌搜索,我可以写以下代码

^{pr2}$

我不确定上面的代码有多高效,因为我们要遍历filecontent两次来检索内容。能做些更有效率的事吗。在


Tags: 文件代码in标记内容todaytitlecontent
1条回答
网友
1楼 · 发布于 2024-04-29 09:32:39

如果要在2个子字符串中找到一个字符串,可以使用remoudle:

import re

myfile = open(files,'r');
filecontent = myfile.read();

results = re.compile('content(.*?)score', re.DOTALL | re.IGNORECASE).findall(filecontent)
print results

一些解释:

IGNORECASE来自文档:

Perform case-insensitive matching; expressions like [A-Z] will match lowercase letters, too. This is not affected by the current locale.

DOTALL来自文档:

^{pr2}$

Compile你可以看到{a1}

还有一些其他的解决方案你可以看到here

相关问题 更多 >