文件中的行下面。
god is great
god is excellent
i am excellent
you are not good
I am also bad
world is 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))
答案 0 :(得分:1)
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']
这会过滤掉test2.txt
文件中在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 ']
如果您只想替换切片行中的words_not_require
中的单词,请使用上面的代码。
此外,使用with
打开文件,这样您就可以不必调用f.close()
。 with
将唤起dunder方法__exit__
来帮助关闭文件
答案 1 :(得分:0)
我相信您想将最后两行更改为:
`import logging.Logger.info
class Project(name: String, daysToComplete: Int)
class Test {
val project1 = new Project("TPS Reports", 1)
val project2 = new Project("Website redesign", 5)
info("Created projects") // Prints "INFO: Created projects"
}`
输出:
for j in list3:
print(' '.join([word for word in lines[j].split() if word not in words_not_require]))