用正则表达式提取特定行下面行上的数字?

2024-06-08 21:25:01 发布

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

如果文本文件中有以下行:

5 HIV serotype 2
    3838 28282 4949
        383 292 1012

10 SIV unknown serotype
    3939 433 332 3222 122
       3221 222 345 433 393 303

…我想从5个HIV血清型线以下和10个SIV未知血清型线以上提取数字,我假设以下方法可行:

import re
with open('test.dat', 'r') as f:
        line = line.strip()
        if re.match('\d\s+HIV.*?(\d+)', line, re.MULTILINE):
            print(re.match())

但是,什么也没有返回。你知道吗

谢谢你。你知道吗


Tags: 方法testimportrematchwithline数字
3条回答

如果您非常确定这些行以这种格式存在于您的文件中,那么您就不需要regex了。只需使用takewhiledropwhile模块中的itertools函数即可:

In [131]: with open('test.txt') as f:
              dropwhile(lambda x: x.startswith('5 HIV serotype'), f); next(f)
              lines = takewhile(lambda x: not x.startswith('10 SIV unknown'), f)
              print([j for l in lines for j in l.strip().split() if j])
   .....:     
['3838', '28282', '4949', '383', '292', '1012']

注意,在处理大数据时,his是一种非常优化内存和运行时的方法。你知道吗

使用re.findallre.searchre.search完成匹配HIV部分的工作,其中re.findall从匹配的部分中选择数字。你知道吗

>>> import re
>>> s = '''5 HIV serotype 2
    3838 28282 4949
        383 292 1012

10 SIV unknown serotype
    3939 433 332 3222 122
       3221 222 345 433 393 303'''
>>> re.findall(r'\d+', re.search(r'(?s)\d+\s+HIV\s+(.*?)(?:\n\n|$)', s).group(1))
['2', '3838', '28282', '4949', '383', '292', '1012']
>>> 

尝试以下代码(解释为注释):

with open("serotypes.txt", "r") as ff:
    lines = ff.read().split("\n")                   # read file and split lines;
lines = list(map(lambda x: x.strip(), lines))       # trim each line;
lines.reverse()                                     # reverse the list for pop to work below;
outlist = []        # empty output list;
try:                                    
    while True:     # keep reading till exception occurs due to empty lines list
        while True:
            i = lines.pop()                         # ignore all till HIV Line;
            if i.startswith("5 HIV serotype"):              
                outlist.append(i.split("5 HIV serotype")[1].strip())    # append last number of HIV Line;
                break
        while True:
            i = lines.pop()
            if i.startswith("10 SIV unknown serotype"):     # if SIV line found, break out;
                break
            else:
                outlist.extend(i.split())                   # extend (not append) all lines till then to output list;
except:
    pass
print(outlist)

'文件的输出'血清型.txt'包含许多文本块:

['2', '3838', '28282', '4949', '383', '292', '1012', '2', '3838', '28282', '4949', '383', '292', '1012', '2', '3838', '28282', '4949', '383', '292', '1012', '2', '3838', '28282', '4949', '383', '292', '1012']

相关问题 更多 >