在文件中有下面的行
god is great
god is excellent
i am excellent
you are not good
I am also bad
world is awesome
在所有这些行中,我需要填充下面三行,但这些行不应该与“good”和“awesome”这样的词相匹配
这是密码。但它并没有像预期的那样起作用
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))
这会过滤掉
test2.txt
文件中包含words_not_require
中单词的行如果您只想替换切片行中
words_not_require
中的单词,请使用上面的代码另外,使用
with
打开文件,这样您就不用调用f.close()
with
将调用dunder方法__exit__
来帮助关闭文件我想你应该把最后两行改成:
输出:
相关问题 更多 >
编程相关推荐