在文件中搜索单词并打印匹配行 - Python

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

我是Python新手,我正在尝试在文件中找到一个单词并打印“整个”匹配行

exmaple.txt 有以下文本:

sh version

Cisco IOS Software, 2800 Software (C2800NM-IPBASE-M), Version 12.4(3h), RELEASE SOFTWARE (fc2)

sh inventory

NAME: "2811 chassis", DESCR: "2811 chassis, Hw Serial#: FHK1143F0WY, Hw 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "16 Port 10BaseT/100BaseTX EtherSwitch"

要求: 查找字符串“Cisco IOS Software”,如果找到则打印该完整行。 在文件中查找“NAME:”,如果找到则打印该完整行并计算出现的次数

代码:

import re
def image():
    file = open(r'C:\Users\myname\Desktop\Python\10_126_93_132.log', 'r')
    for line in file:
        if re.findall('Cisco IOS Software', line) in line:
            print(line)
        else:
            print('Not able to find the IOS Information information')

def module():
    file = open(r'C:\Users\myname\Desktop\Python\10_126_93_132017.log', 'r')
    for line in file:
        if re.findall('NAME:') in line:
            print(line)
        else:
            print('No line cards found')

错误:

Traceback (most recent call last):
File "C:/Users/myname/Desktop/Python/copied.py", line 19, in <module>image()
File "C:/Users/myname/Desktop/Python/copied.py", line 5, in image if re.findall('Cisco IOS Software', line) in line:
TypeError: 'in <string>' requires string as left operand, not list
python search findall
2个回答
6
投票

可能这就是您正在寻找的:

import re
with open('some_file', 'r') as f:
    lines = f.readlines()
    for line in lines:
        if re.search(r'some_pattern', line):
            print line
            break

请参阅搜索了解更多详情

顺便说一句:你的问题非常难以理解。在按下提问按钮之前,您应该检查如何以正确的方式发布您的问题。


1
投票

简单的方法:

with open('yourlogfile', 'r') as fp:
    lines = fp.read().splitlines()
    c = 0
    for l in lines:
        if 'Cisco IOS Software' in l or 'NAME:' in l:
            print(l)
        if 'NAME:' in l: c += 1
    print('\nNAME\'s count: ', c)

输出:

Cisco IOS Software, 2800 Software (C2800NM-IPBASE-M), Version 12.4(3h), RELEASE SOFTWARE (fc2)
NAME: "2811 chassis", DESCR: "2811 chassis, Hw Serial#: FHK1143F0WY, Hw 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "High Speed Wan Interface card with 16 RS232 async ports(HWIC-16A)", 
NAME: "16 Port 10BaseT/100BaseTX EtherSwitch"

NAME's count:  4
© www.soinside.com 2019 - 2024. All rights reserved.