在python中按特定顺序查找子字符串

我有一长串字符串,其中包含按给定顺序排列的感兴趣的子字符串,但这里有一个在文本文件中使用句子的小例子:


This is a long drawn out sentence needed to emphasize a topic I am trying to learn.

It is new idea for me and I need your help with it please!

Thank you so much in advance, I really appreciate it.

从这个文本文件,我想找到同时包含任何句子"I"和"need",但他们必须在出现的顺序。


因此,在这个例子中,'I'并且'need'都发生在第1句和第2句,但句子1他们是在错误的顺序,所以我不想返回。我只想'I need'按顺序返回第二句话。


我用这个例子来识别子字符串,但我不知道如何只按顺序找到它们:


id1 = "I"

id2 = "need"


with open('fun.txt') as f:

    for line in f:

        if id1 and id2 in line:

            print(line[:-1])

这将返回:


This is a long drawn out sentence needed to emphasize a topic I am trying to learn.

It is new idea for me and I need your help with it please!

但我只想:


It is new idea for me and I need your help with it please!

谢谢!


幕布斯6054654
浏览 250回答 3
3回答

慕盖茨4494581

您可以使用正则表达式来检查这一点。一种可能的解决方案是:id1 = "I"id2 = "need"regex = re.compile(r'^.*{}.*{}.*$'.format(id1, id2))with open('fun.txt') as f:    for line in f:        if re.search(regex, line):            print(line[:-1])

慕无忌1623718

您需要确定id2在该行的部分后 id1:infile = [    "This is a long drawn out sentence needed to emphasize a topic I am trying to learn.",    "It is new idea for me and I need your help with it please!",    "Thank you so much in advance, I really appreciate it.",]id1 = "I"id2 = "need"for line in infile:    if id1 in line:        pos1 = line.index(id1)        if id2 in line[pos1+len(id1) :] :            print(line)输出:It is new idea for me and I need your help with it please!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python