2013-03-14 57 views
0

我想解析python中的字符串。我已经发布了一些关于堆栈溢出的问题,我基本上试图将所有解析我正在使用的字符串的不同可能方式的功能结合起来。python的字符串解析不一致

下面是一个代码片段,它可以很好地解析以下两种字符串格式。

from __future__ import generators 
from pprint import pprint 
s2="<one><two><three> an.attribute ::" 
s1="<one> <two> <three> here's one attribute < six : 10.3 > < seven : 8.5 > < eight : 90.1 > < nine : 8.7 >" 
def parse(s): 
    for t in s.split('<'): 
     for u in t.strip().split('>',1): 
      if u.strip(): yield u.strip() 
pprint(list(parse(s1))) 
pprint(list(parse(s2))) 

这里是我得到的输出。这是我需要的格式,每个属性存储在不同的索引位置。

['one', 
'two', 
'three', 
"here's one attribute", 
'six : 10.3', 
'seven : 8.5', 
'eight : 90.1', 
'nine : 8.7'] 
['one', 'two', 'three', 'an.attribute ::'] 

这是完成后,我试图合并相同的代码转换成可解析四种弦格式,但由于某种原因,它似乎并没有在这里工作,我无法弄清楚,为什么一个功能。

以下是整个代码。

from __future__ import generators 
import re 
import string 
from pprint import pprint 
temp=[] 
y=[] 
s2="<one> <two> <three> an.attribute ::" 
s1="<one> <two> <three> here's an attribute < four : 6.5 > < five : 7.5 > < six : 8.5 > < seven : 9.5 >" 
t2="<one> <two> <three> < four : 220.0 > < five : 6.5 > < six : 7.5 > < seven : 8.5 > < eight : 9.5 > < nine : 6 - 7 >" 
t3="One : two : three : four Value : five Value : six Value : seven Value : eight Value :" 
def parse(s): 
    c=s.count('<') 
    print c 
    if c==9: 
     res = re.findall('< (.*?) >', s) 
     return res 
    elif (c==7|c==3): 
     temp=parsing(s) 
     pprint(list(temp)) 
     #pprint(list(parsing(s))) 
    else: 
     res=s.split(' : ') 
     res = [item.strip() for item in s.split(':')] 
     return res 
def parsing(s): 
    for t in s.split(' < '): 
     for u in t.strip().split('>',1): 
      if u.strip(): yield u.strip() 
    pprint(list((s))) 

现在,当我编译代码和调用parse(s1)我得到以下的输出:

7 
["<one> <two> <three> here's an attribute < four", 
'6.5 > < five', 
'7.5 > < six', 
'8.5 > < seven', 

同样,在调用parse(s2),我得到:

3 
['<one> <two> <three> an.attribute', '', ''] 
    '9.5 >'] 

为什么会出现在分析字符串时分裂字符串时出现不一致?我在两个地方使用相同的代码。

有人能帮我弄清楚为什么会发生这种情况吗? :)

+0

令我惊讶的第一件事 - 您使用的是什么版本的Python!? 'from __future__ import generators'意味着* anicent * – 2013-03-14 10:00:19

+0

我正在使用PyScripter 2.7。你建议我用什么来代替? :) @JonClements – Anon 2013-03-14 10:05:27

+0

你*不*需要使用从'__future__导入发电机'行*在所有*然后。 – 2013-03-14 10:07:44

回答

2

您使用的是二进制|按位或操作员,你应该使用,而不是or布尔运算符:

elif (c==7|c==3): 

应该

elif c==7 or c==3: 

或者是:

elif c in (3, 7): 

这是更快启动。

因为|操作符比or运营商不同优先级,第一个发言被解读为(c == (7 | c) == 3)7 | c做逻辑运算,返回结果是从未要等于两c3,使总是回报False

>>> c = 7 
>>> (c==7|c==3) 
False 
>>> c = 3 
>>> (c==7|c==3) 
False 
>>> c==7 or c==3 
True 
+0

是的,那是错的。非常感谢,我是Python的新手,我仍然在寻找解决方法=)@Martijn Pieters – Anon 2013-03-14 10:08:24

+0

@Paulie同样值得注意的是'c == 7 | c == 3 | c == 9 | c == 2'等...可以更Python的写成'c in(7,3,9,2)' - 这更清晰,并且使添加/删除条件更容易 – 2013-03-14 10:10:26

+0

真棒,谢谢:) @JonClements – Anon 2013-03-14 10:51:57