2017-06-22 7 views
-1

私は、Pythonの初心者です、と私は「全体」マッチラインexmaple.txtがあり検索 - Pythonの

にファイル内の単語を検索し、印刷しようとしています次のテキスト:

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ソフトウェア」を検索し、印刷するには、その完全なラインを発見した場合。

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 
+0

're.findall()'はリストを返します。 '行の場合のみ' – kuro

答えて

0

シンプルなアプローチ:

検索 "NAME:" 完全なライン&が出現

コードの数をカウントし、ファイル内とIFた印刷

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 
+0

あなたの返事に感謝します:) – Vadiraj

1

おそらくそれはあなたが探しているものです:ところで

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

:あなたの質問は非常に読めないです。質問の質問ボタンを押す前に、質問を適切な方法で投稿する方法を確認する必要があります。

+0

確かに、それをチェックします:) – Vadiraj