私はPythonで次の2つの文字列を解析しようとしています:
これが最初の文字列です
s1="< one > < two > < three > here's one attribute < six : 10.3 > < seven : 8.5 > < eight : 90.1 > < nine : 8.7 >"
上記を分割して次のようなリストに格納できるように、reが必要です。ここで、下の新しい行の各項目は、リスト内の特定のインデックスの要素です。
0 one
1 two
2 three
3 here's one attribute
4 six : 10.3
5 seven : 8.5
6 eight : 90.1
7 nine : 8.7
これが2番目の文字列です
s2="<one><two><three> an.attribute ::"
同様に、次のようなリストにアイテムを保存する必要があります。
0 one
1 two
2 three
3 an.attribute
これが私がこれまでに試したことです。これは、StackOverflowに投稿した別の質問から得た回答です。
res = re.findall('< (.*?) >', s1)
pprint(res)
index=0
for index in res:
print index
しかし、それは「ここに1つの属性があります」をスキップします
出力:
['one', 'two', 'three', 'six : 10.3', 'seven : 8.5', 'eight : 90.1', 'nine : 8.7']
one
two
three
six : 10.3
seven : 8.5
eight : 90.1
nine : 8.7
誰か助けてもらえますか?=)
最初の文字列から10.3、8.5、90.1、8.7のような文字列から数値を抽出する方法を誰かが知っているなら、それも素晴らしいでしょう=)
編集:ダンカン私はあなたのコードを試しましたが、私は私がすべきように出力を取得していないようです。どこかでなんらかの間違いをしたと思います。それが何であるか教えてもらえますか?
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()
list(parse(s1))
list(parse(s2))
pprint(s1)
pprint(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 ::'