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

Python 使用正则表达式提取特定行下方行上的数字?,python,regex,python-3.x,Python,Regex,Python 3.x,如果文本文件中有以下行: 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:

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

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())
但是,没有返回任何内容


谢谢。

使用
re.findall
re.search
re.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']
>>> 

如果您非常确定这些行以这种格式存在于文件中,那么就不需要正则表达式。您只需使用
itertools
模块中的
takewhile
dropwhile
功能即可:

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在内存和运行时间方面都是一种非常优化的方法。

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

包含许多文本块的文件“serotypes.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']

我期待以下数字串: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', '2', '3838', '28282', '4949', '383', '292', '1012']