2010-11-04 33 views
0

我有一行一行的文本,其中包含许多字段名称和它们的值,如下所示:如果任何行没有任何字段值,则该字段不会存在于该行中 例如从python中的字符串中提取字段

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 

但确认最多3个字段是可能的单行,他们的名字将是A,B,TS。当我为这个编写python脚本时,我遇到了下面的问题: 1)我必须从每一行中提取哪些字段存在以及它们的值是什么 2)字段TS的字段值也具有分隔符''(空格) 。所以无法检索TS的全部价值(1990年1月1日22点22分22秒)

输出valueshould提取像

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 

请帮我解决这个问题。

+1

这是真的,但这是一个理由downvote他的问题?我觉得它非常有效。而且,如果你不断下调他的表现,他就失去了获胜的权利,我们不想要这样做,对吗? :) – 2010-11-04 09:04:52

回答

2
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} 

将输出

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

正则表达式的说明:

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

感谢您的帮助,它解决了我的问题 – james 2010-11-04 09:29:08

+0

在继续上面的线程,我有下面的行| | |答:720897 | N°227:AT圈,我用regex = re.compile(r“\ s *(?:(Link Id)\ s *:\ s *(\ d +))\ s * | \ s *(?: (N°(\ D +))\ S *:\ S *(。*))$“),但它没有给出所需的结果.pls让我知道我错在哪里。我已经使用# - * - 编码:ISO -8859-1 - * - – james 2010-11-09 07:13:27

+0

@james:代码格式化在评论中很难;你能编辑你的答案并将你的新例子格式化为代码,所以我可以更好地看到问题出在哪里?谢谢。 – 2010-11-09 08:42:41

1

您可以使用正则表达式,如果每次假定订单的顺序相同,则可以使用正则表达式,否则如果您不确定订单,则必须单独匹配每个零件。

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") 

这打印出来{'A': '30', 'B': '40', 'TS': '1/1/1990 22:22:22'}这只是一个包含值的字典。

P.S.你应该接受一些答案并熟悉网站的礼节,人们会更愿意帮助你。