作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个很长的字符串列表,其中包含按给定顺序排列的感兴趣的子字符串,但这里是一个使用文本文件中的句子的小示例:
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/
我正在尝试开发右边框/Angular 具有特定 Angular (30°) 的表格。我见过一些类似的解决方案,但它们都无法在一定程度上发挥作用。如果我想从 30° 改变到 20°,我不想花太多力气。
我是一名优秀的程序员,十分优秀!