如何在一行中搜索一个词,即使它是 python 中一个更大词的一部分[重复]

问题描述 投票:0回答:1

我有一个文件 1,其文本如下

boy men women
girl women men

我有一个文件 2,其文本如下

good babyboy
good babygirl
bad babyboy
bad babygirl
xyz
abc

现在我想在 file2 中搜索 file1 中第一个单词(男孩或女孩)以及单词 good 的行,并在 file3 中打印出这些行。

file3 应该有

good babyboy
good babygirl

有人可以帮我写代码吗

我试过下面那个

def main():
    input_file_1 = 'file1'
    input_file_2 = 'file2'
    output_file = 'file3'

    with open(input_file_1, 'r') as f:
        lines_1 = f.readlines()
    with open(input_file_2, 'r') as f:
        lines_2 = f.readlines()
    with open(output_file, 'w') as f:
        for line_1 in lines_1:
            words = line_1.split()
            for line_2 in lines_2:
                if words[0] in line_2:
                    if 'good' in line_2:
                        f.write(line_2)

我没有得到任何输出:(

python string file search line
1个回答
-2
投票

试试这个代码:

def main():
    input_file_1 = 'file1'
    input_file_2 = 'file2'
    output_file = 'file3'

    with open(input_file_1, 'r') as f:
        lines_1 = f.readlines()
    with open(input_file_2, 'r') as f:
        lines_2 = f.readlines()
    with open(output_file, 'w') as f:
        for line_1 in lines_1:
            words = line_1.strip().split()
            if words[0] in ['boy', 'girl']:
                for line_2 in lines_2:
                    if words[0] in line_2 and 'good' in line_2:
                        f.write(line_2)
                f.seek(0)
© www.soinside.com 2019 - 2024. All rights reserved.