匹配单词行不考虑在最终列表中,而是基于索引值

2024-05-14 12:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在文件中有下面的行

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))  

Tags: inforifislinenotamawesome
2条回答
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__来帮助关闭文件

我想你应该把最后两行改成:

for j in list3:
    print(' '.join([word for word in lines[j].split() if word not in words_not_require]))

输出:

you are not
I am also bad
world is

相关问题 更多 >

    热门问题