2014-01-06 64 views
3

我解析这个line -解析此字符串的Pythonic方式?

0386   ; Greek # L&  GREEK CAPITAL LETTER ALPHA WITH TONOS 

基本上,我需要 -

point = 0386 
script = Greek 

而我做这个样子,

point = line.split(";")[0].replace(" ","") 
script = line.split("#")[0].split(";")[1].replace(" ","") 

我不相信我正在做的是做这件事最pythonic的方式,是否有一个更优雅的方式做到这一点?也许是一个正则表达式?

回答

2

使用map与不受约束的方法str.strip

>>> line = '0386  ; Greek # L& GREEK CAPITAL LETTER ALPHA WITH TONOS' 
>>> point, script = map(str.strip, line.split('#')[0].split(';')) 
>>> point 
'0386' 
>>> script 
'Greek' 

使用列表理解:

>>> point, script = [word.strip() for word in line.split('#')[0].split(';')] 
>>> point 
'0386' 
>>> script 
'Greek' 
+1

这看起来很简洁,但我更喜欢不使用'map'。 –

+0

@GamesBrainiac,我添加了列表理解版本。 – falsetru

+0

@GamesBrainiac为什么不是'map'?它会如何影响性能? – ComputerFellow

0

这是我会怎么做了吧:

>>> s = "0386   ; Greek # L&  GREEK CAPITAL LETTER ALPHA WITH TONOS" 
>>> point = s.split(';')[0].strip() 
>>> point 
'0386' 
>>> script = s.split(';')[1].split('#')[0].strip() 
>>> script 
'Greek' 

请注意,您可以重新使用s.split(';')。因此,也许它保存到var将是一个不错的主意:

>>> var = s.split(';') 
>>> point = var[0].strip() # Strip gets rid of all the whitespace 
>>> point 
'0386' 
>>> script = var[1].split('#')[0].strip() 
>>> script 
'Greek' 
+1

原因downvote? –

3

如果你想有一个正则表达式一个班轮:

point, script = re.search("^(\d+)\s*;\s*(\S+)\s*.*$",s).groups() 

其中s是你的字符串,当然你需要import re

+0

+1 nothing like good ol正规表达式:) –

+0

'(“^(。*)\ s +; \ s +(。*)\ s +#。* $”,s).groups()'为我工作。以上没有。 – ComputerFellow

+1

@ComputerFellow,你的正则表达式匹配后面的空格。但如果它适合你,我很高兴!无论如何,这里的要点是要展示如何用一条正则表达式来处理它。 – EyalAr

3
>>> code, desc = line[:line.rfind('#')].split(';') 
>>> code.strip() 
'0386' 
>>> desc.strip() 
'Greek' 
+0

现在_this_是优雅的。布尔汉,你有我的投票! :d –