如何使用正则表达式在 Python 3 中的特定字符串之后或之前找到一行?

如何使用正则表达式在python3中的特定字符串之前或之后找到一行?我正在阅读文本文件中的内容,请帮助我


文件.txt


my name is dharshini

my mom name is chandra

my dad name is uday

my anniversay is on 04/01/1997

import re


with open('file.txt','r') as f:

input_file = f.readlines()


for line in input_file :

 find_line = re.findall(r'(mom)', line)

 print(next-1(line))

 print(next(line))

 print(next(line))

预期输出:


my name is dharshini

my dad name is uday

my anniversay is on 04/01/1997


神不在的星期二
浏览 137回答 2
2回答

波斯汪

尝试使用enumerate,enumerate在循环时获取索引,因此我获取索引并通过索引和切片获取其余值:for i,line in enumerate(paragraph):    if 'mom' in line:        print(paragraph[:i])        print(paragraph[i:])编辑:with open('file.txt','r') as f:    input_file = f.readlines()    for i,line in enumerate(input_file):        line=line.rstrip()        if 'mom' in line:            print(paragraph[:i])            print(paragraph[i:])

Helenr

试试这个:import reparagraph = ["my name is dharshini", "my mom name is chandra", "my dad name is uday" ,  "my anniversay is on 04/01/1997" ]#set a flag for laterprint_next = Falsefor line in paragraph: find_line = re.findall(r'(mom)', line) #if mom is found dad will be next if print_next:     print(line)     print_next = False #if mom is found if len(find_line) > 0:     print(line)     print_next = True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python