在行内搜索特定的短语模式。python

2024-03-29 08:48:22 发布

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

我已经制定了一些需要在文件中搜索的规则。这些规则本质上是包含未知数量单词的短语。例如

mutant...causes(...)GS

这里,这是一个短语,我想在我的文件中搜索。...表示这里应该有几个单词(即在这个空白处)&(...)表示这个空白处可能有/可能没有单词。GS这是一个我知道的固定字符串变量。在

基本上,我是通过浏览许多这样的文件来制定这些规则的,它们告诉我,某个特定的文件可以满足我的需要。在

问题是这个间隙可以有任何(小)个单词。甚至可以有一条新的线从一个空白处开始。因此,我不能使用相同的字符串匹配。在

一些示例文本-

  1. !Series_summary "To better understand how the expression of a *mutant gene that causes ALS* can perturb the normal phenotype of astrocytes, and to identify genes that may

这里的GS是ALS(defined),加星号的文本应该是规则mutant...causes(...)GS的正匹配

  1. !Series_overall_design "The analysis includes 9 samples of genomic DNA from isolated splenic CD11c+ dendritic cells (>95% pure) per group. The two groups are neonates born to mothers with *induced allergy to ovalbumin*, and normal control neonates. All neonates are genetically and environmentally identical, and allergen-naive."

这里的GS是卵清蛋白(已定义),带星号的文本应该是规则的正匹配 induced...to GS

我是Python编程初学者,所以任何帮助都太好了!在


Tags: and文件oftheto字符串文本gs
1条回答
网友
1楼 · 发布于 2024-03-29 08:48:22

下面的步骤应该让您开始,它将读取您的文件并使用Pythonregular expression显示所有可能的匹配行,这将帮助您确定它是否匹配所有正确的行:

import re

with open('input.txt', 'r') as f_input:
    data = f_input.read()
    print re.findall(r'(mutant\s.*?\scauses.*?GS)', data, re.S)

要只搜索一个匹配项的存在,请将findall更改为search

^{pr2}$

要在许多这样的文件上执行此操作,可以按如下方式对其进行调整:

import re
import glob

for filename in glob.glob('*.*'):
    with open(filename, 'r') as f_input:
        data = f_input.read()
        if re.search(r'mutant\s.*?\scauses.*?GS', data, re.S):
            print "'{}' matches".format(filename)

相关问题 更多 >