我有一个文本文件,我需要在其中搜索单词' insert'和'条件'。
***code***
word='insert'
word1='condition'
i=[]
c=[]
with open(filename,'r') as searchfile:
for line in searchfile:
if word in line:
i.append(line)
if word in line:
## here i am searching for next insert before condition.
## if i get insert before condition,i pop the previous inserted line
## and append the new one
i.pop()
i.append(line)
if word1 in line:
c.append(line)
print c
print i
***code ends***
输入文字示例 插入hello1 条件是,它是hello1
插入hello2 插入hello3 插入hello4 条件是,它是hello4
示例输出 在列表中我不想插入hello2并插入hello3,因为它们没有条件。考虑到2个列表i []和c [],我希望列表包含
i = ['插入hello1,'插入hello4'] c = ['条件是,它是hello1','条件是,它是hello4' ]
答案 0 :(得分:0)
我的问题不明确,你没有回复我的评论。如果这不是您要查找的程序,请发表评论并让我对其进行修改。
<强> input.txt中:(样品)强>
插入插入hello1
插入条件hello2
插入条件条件2
条件插入hello3
插入
该计划:
substring = "insert condition"
myList=[]
with open("input.txt",'r') as searchfile:
for line in searchfile:
if (substring in line):
myList.append(line)
print myList
<强>输出:强>
>>> ================================ RESTART ================================
>>>
['insert condition hello2\n', 'insert condition condition 2\n']
>>>