Having below lines in a file.
god is great
god is excellent
i am excellent
you are not good
I am also bad
world is awesome
out of all these lines bottom three lines I need to populate but those lines should not match having word like 'good' and 'awesome'.
Here is code. But it doesn't work as expected.
f = open('test2.txt')
lines = [line for line in f.readlines() if line.strip()]
total_lines=len(lines)
index1=[0,1,2]
all_index=list(range(0,total_lines))
list3 = [i for i in all_index if not i in index1] ## Capturing Index (3,4,5)
words_not_require=['good','awesome'] ## Lines matching these words not required in final list
for j in list3:
print (''.join(i for i in lines[j] if i not in words_not_require))
keeplist = []
words_not_require=['good','awesome']
with open('test2.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if not any(word in line for word in words_not_require):
keeplist.append(line)
print (keeplist)
#Output:
#['god is great', 'god is excellent', 'i am excellent', 'I am also bad']
This filters out the lines in your test2.txt
file that has the words in words_not_require
keeplist = []
words_not_require=['good','awesome']
with open('test2.txt', 'r+') as f:
lines = f.readlines()
for line in lines[3:]: #this gives you lines 4 onwards
line = line.strip()
for word in words_not_require:
line = line.replace(word, '')
keeplist.append(line)
print (keeplist)
#Output:
#['you are not ', 'I am also bad', 'world is ']
Use above code if you just want to replace the words in words_not_require
in your sliced lines.
Also, use with
to open your files so that you can skip having to call f.close()
. with
will evoke the dunder method __exit__
to help close the file
I believe you want to change your last two lines to:
for j in list3:
print(' '.join([word for word in lines[j].split() if word not in words_not_require]))
Output:
you are not
I am also bad
world is
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.