matching multiple strings and print results in table

I am trying to write code to match words in a line and print the word i need from that line. like i have

Hostname router1
version 15
xxxx------
Hostname router2
version 14
xxxx------

I know there is problem in loop and correct library to use. Please can some one help me with it. i want to extract Hostname and version in table

Hostname Version
router1    15
router2    14

Note: i need some help in using correct lib for matching/extracting data in a line. my code is :

import re
from prettytable import PrettyTable
with open('testfile.txt','r') as input:
    table = PrettyTable(['Hostname', 'Version'])
    space = ''
    cntr = 1
    for line in input.read().split('\n'):
    match1=re.match(r'Hostname(.*)''|''version(.*)',line,
    re.MULTILINE)
       if match1:
          space = ''
          cntr += 1
          str= (match1.group())

          table.add_row([match1.group(1),match1.group(2)])
          print(table)
       else:
          cntr+=1
          space=space+'\n'+line

1 answer

  • answered 2018-04-17 05:08 Rachit kapadia

    #sample.txt contains following data:
    
    Hostname router1
    version 15
    xxxx------
    Hostname router2
    version 14
    xxxx------
    

    #Code:
    
    import pandas as pd
    df = pd.read_csv("sample.txt", sep=" " , names=["Host", "Version"])
    # print df
    print type(df)
    for item in zip(df["Host"], df["Version"]):
        if "Hostname" in item[0] or "version" in item[0]:
            print(item[0] +  " : " + str(item[1]))
    

    #output:
    Hostname : router1
    version : 15
    Hostname : router2
    version : 14