gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:20:27 25 4
gpt4 key购买 nike

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

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!

谢谢!

最佳答案

您需要在id1:

之后行的部分中识别 id2
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!

关于python - 在python中按一定顺序查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53891062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com