wasima wasima - 2 years ago 58
Python Question

how to take the specific details out in Python that are separated by a semi colon or a slash?

I have the following results from a vet analyser

result{type:PT/APTT;error:0;PT:32.3 s;INR:0.0;APTT:119.2;code:470433200;lot:405
4H0401;date:20/01/2017 06:47;PID:TREKKER20;index:015;C1:-0.1;C2:-0.1;qclock:0;ta

Using Python how do i separate the date the time the type PT and APTT.... please note that the results will be different everytime so i need to make a code that will find the date using the / and will get the time because of four digits and the : .... do i use a for loop?

Answer Source

This code makes further usage of fields easier by converting them to dict.

from pprint import pprint

result = "result{type:PT/APTT;error:0;PT:32.3 s;INR:0.0;APTT:119.2;code:470433200;lot:405 4H0401;date:20/01/2017 06:47;PID:TREKKER20;index:015;C1:-0.1;C2:-0.1;qclock:0;ta rget:2;name:;Sex:;BirthDate:;operatorID:;SN:024000G0900046;version:V2.8.0.09}"

if result.startswith("result{") and result.endswith("}"):
    result = result[(result.index("{") + 1):result.index("}")]
# else:
#    raise ValueError("Invalid data '" + result + "'")

# Separate fields
fields = result.split(";")
# Separate field names and values
# First part is the name of the field for sure, but any additional ":" must not be split, as example "date:dd/mm/yyyy HH:MM" -> "date": "dd/mm/yyyy HH:MM"
fields = [field.split(":", 1) for field in fields]
fields = {field[0]: field[1] for field in fields}

a = fields['type'].split("/")


The result:

{'type': 'PT/APTT', 'error': '0', 'PT': '32.3 s', 'INR': '0.0', 'APTT': '119.2', 'code': '470433200', 'lot': '405 4H0401', 'date': '20/01/2017 06:47', 'PID': 'TREKKER20', 'index': '015', 'C1': '-0.1', 'C2': '-0.1', 'qclock': '0', 'ta rget': '2', 'name': '', 'Sex': '', 'BirthDate': '', 'operatorID': '', 'SN': '024000G0900046', 'version': 'V2.8.0.09'}
{'APTT': '119.2',
 'BirthDate': '',
 'C1': '-0.1',
 'C2': '-0.1',
 'INR': '0.0',
 'PID': 'TREKKER20',
 'PT': '32.3 s',
 'SN': '024000G0900046',
 'Sex': '',
 'code': '470433200',
 'date': '20/01/2017 06:47',
 'error': '0',
 'index': '015',
 'lot': '405 4H0401',
 'name': '',
 'operatorID': '',
 'qclock': '0',
 'ta rget': '2',
 'type': 'PT/APTT',
 'version': 'V2.8.0.09'}
['PT', 'APTT']

Note that dictionaries are not sorted (they don't need to be in most cases as you access the fields by the keys).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download