开发者

Extract fields from the string in python

I have text line by line which contains many field name and their value seperated by : , if any line does not have any field value then that field would not exist in that line for example

First line:
A:30 B: 40 TS:1/1/1990 22:22:22
Second line
A:30 TS:1/1/1990 22:22:22
third line
A:30 B: 40

But it is confirmed that at max 3 fields are possible in single line and their name will be A,B,TS. while writing python script for this, i am facing below issues: 1) I have to extract from each line which are the fie开发者_运维技巧ld exist and what are their values 2) Field value of field TS also have seperator ' '(SPACE).so unable retrieve full value of TS(1/1/1990 22:22:22)

Output valueshould be extracted like that

First LIne:
A=30
 B=40
 TS=1/1/1990 22:22:22

Second Line:
A=30

 TS=1/1/1990 22:22:22

Third Line
A=30
 B=40

Please help me in solving this issue.


import re
a = ["A:30 B: 40 TS:1/1/1990 22:22:22", "A:30 TS:1/1/1990 22:22:22", "A:30 B: 40"]
regex = re.compile(r"^\s*(?:(A)\s*:\s*(\d+))?\s*(?:(B)\s*:\s*(\d+))?\s*(?:(TS)\s*:\s*(.*))?$")
for item in a:
    matches = regex.search(item).groups()
    print {k:v for k,v in zip(matches[::2], matches[1::2]) if k}

will output

{'A': '30', 'B': '40', 'TS': '1/1/1990 22:22:22'}
{'A': '30', 'TS': '1/1/1990 22:22:22'}
{'A': '30', 'B': '40'}

Explanation of the regex:

^\s*      # match start of string, optional whitespace
(?:       # match the following (optionally, see below)
 (A)      # identifier A --> backreference 1
 \s*:\s*  # optional whitespace, :, optional whitespace
 (\d+)    # any number --> backreference 2
)?        # end of optional group
\s*       # optional whitespace
(?:(B)\s*:\s*(\d+))?\s*  # same with identifier B and number --> backrefs 3 and 4
(?:(TS)\s*:\s*(.*))?     # same with id. TS and anything that follows --> 5 and 6
$         # end of string


You could use regular expressions, something like this would work if the order was assumed the same every time, otherwise you would have to match each part individually if you're unsure of the order.

import re

def parseInput(input):
    m = re.match(r"A:\s*(\d+)\s*B:\s*(\d+)\s*TS:(.+)", input)
    return {"A": m.group(1), "B": m.group(2), "TS": m.group(3)}

print parseInput("A:30 B: 40 TS:1/1/1990 22:22:22")

This prints out {'A': '30', 'B': '40', 'TS': '1/1/1990 22:22:22'} Which is just a dictionary containing the values.

P.S. You should accept some answers and familiarize yourself with the etiquette of site and people will be more willing to help you out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜