简体   繁体   中英

Extract data from a field in a text file in Python

I am new to Python. I want to know what is the best way to extract data from a field in a text file?

My text file saves the information of a network. It looks like this:

Name: Machine_1 Status: On IP:10.0.0.1
Name: Machine_2 Status: On IP:10.0.0.2
Network_name: Private Router_name: router1 Router_ID=3568
Subnet: Tenant A

The file is not very structured. It cannot even be expressed as a CSV file due to non-homogeneous nature of rows ie all of them do not have the same column identifiers.

What I want to do is to be able to get the value of any field I want eg Router_ID.

Please help me find a solution to this.

Thanks.

You could use regular expressions to scan through your file. You'd have to define a regular expression for each field you want to extract. For example:

import re
data = """Name: Machine_1 Status: On IP:10.0.0.1
Name: Machine_2 Status: On IP:10.0.0.2
Network_name: Private Router_name: router1 Router_ID=3568
Subnet: Tenant A"""
for line in data.split('\n'):
    ip = re.match('.*IP:(\d+.\d+.\d+.\d+)', line)
    rname = re.match('.*Router_name: (\w+)', line)
    if ip and ip.lastindex > 0: 
        print(ip.group(1))
    if rname and rname.lastindex > 0:
        print(rname.group(1))

Output:

10.0.0.1
10.0.0.2
router1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM