我想解析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 >']
为什么会出现在分析字符串时分裂字符串时出现不一致?我在两个地方使用相同的代码。
有人能帮我弄清楚为什么会发生这种情况吗? :)
令我惊讶的第一件事 - 您使用的是什么版本的Python!? 'from __future__ import generators'意味着* anicent * – 2013-03-14 10:00:19
我正在使用PyScripter 2.7。你建议我用什么来代替? :) @JonClements – Anon 2013-03-14 10:05:27
你*不*需要使用从'__future__导入发电机'行*在所有*然后。 – 2013-03-14 10:07:44