如何使用Python在文本文件中搜索单词并打印行的一部分?

4

我是一名Python脚本编写者。我需要在一个文本文件中搜索单词并打印该行的一部分。我的问题是,文本文件中的单词不会精确匹配。

举个例子,在下面这个文本文件示例中,我正在搜索单词"color="

文本文件示例:

ip=10.1.1.1 color=red house=big
ip=10.1.1.2 color=green house=small
ip=10.1.1.3 animal = dog house=beach
ip=10.1.1.4 color=yellow house=motorhome

如果找到该内容,应该将"color=color"打印到一个新的文本文件中,而不是整行。
结果文本文件示例:
color=red
color=green
color=yellow

我的代码:

for line_1 in open(file_1):
    with open(line_1+'.txt', 'a') as my_file:
        for line_2 in open(file_2):
            line_2_split = line_2.split(' ')
            if "word" in line_2:
                if "word 2" in line_2:
                    for part in line_2:
                        line_part = line_2.split(): #AttributeError: 'list' object has no attribute 'split'
                        if "color=" in line_part():
                            print(line_part)

我认为我需要使用正则表达式或类似于line.find("color=")的内容,但我不确定具体如何操作。

问题: 我如何搜索文本文件中的单词(不是完全匹配),并仅打印每行中特定的部分?

2个回答

11

这里有一种方法 - 将每行按空格拆分,然后搜索每个部分是否包含 "color=":

with open("textfile.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if "color=" in part:
                print part

我遇到了错误:AttributeError: 'list' object has no attribute 'split',因为我已经在之前对该行进行了分割。我将编辑上面的代码以显示整个代码。 - hjames
那改变了很多。你打开的三个文件中哪一个包含了你上面提到的数据? - Brionius

2

虽然不是太多,但您可以始终使用正则表达式:

m = re.search(r'(color\=.+?(?= )|color\=.+?$)', line)
if m:
    text = m.group() # Matched text here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接