如何在文本文件中搜索单词并用Python打印部分行?
我正在写一个Python脚本。我需要在文本文件中搜索一个单词,然后打印该行的一部分。我的问题是这个词在文本文件中不完全匹配 例如,在下面的文本文件示例中,我正在搜索单词如何在文本文件中搜索单词并用Python打印部分行?,python,python-3.x,Python,Python 3.x,我正在写一个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 c
“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=red
color=green
color=yellow
如果找到它,它应该打印到一个新的文本文件“color=color”
,而不是整行
结果文本文件ex:
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=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=)
,但我不确定是什么或如何使用
问题:如何在文本文件中搜索一个单词(不是完全匹配的),并且只打印每行的特定部分?这里有一种方法-将每行按空格分割,然后在每个部分搜索“color=”:
嗯,可能不多,但您可以始终使用正则表达式:
m = re.search(r'(color\=.+?(?= )|color\=.+?$)', line)
if m:
text = m.group() # Matched text here
我收到错误:
AttributeError:'list'对象没有属性“split”
,因为我以前已经拆分了行。我将编辑上面的代码以显示整个代码。这会改变很多。您正在打开的3+个文件中,哪一个包含上述数据?