为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

幕布斯6054654 2021-09-23 09:27:44
我有一长串字符串,其中包含按给定顺序排列的感兴趣的子字符串,但这里有一个在文本文件中使用句子的小例子: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!谢谢!
查看完整描述

3 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

您可以使用正则表达式来检查这一点。一种可能的解决方案是:


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])


查看完整回答
反对 回复 2021-09-23
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您需要确定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!


查看完整回答
反对 回复 2021-09-23
  • 3 回答
  • 0 关注
  • 249 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信