Belirli bir sistemden bir günlük içeren bir çok büyük bir dizem var
Yalnızca <status>
ile başlayan ve </status>
ile biten parçayı istiyorum.
RegEx ifadesinin iyi bir yol olduğunu duydum, ancak bunu nasıl kullanacağımı gerçekten bilmiyorum.
Herhangi bir fikrin var mı?İki dizenin içine bir alt dizgi alın
cevap
s = "Hello I am a very long string <status>I've got a lovely bunch of coconuts</status> here they are standing in a row"
excerpt = s.partition("<status>")[2].rpartition("</status>")[0]
print excerpt
Sonuç:
I've got a lovely bunch of coconuts
<status>
ve </status>
yalnızca bir oluşum varsa, o zaman string_name[string_name.index("<status>") + 8: string_name.index("</status>"]
kullanabilirsiniz.
s = "test<status>test2</status>"
print s[s.index("<status>") + 8: s.index("</status>"]
Çıktı:
test2
Eğer regex denemek isterseniz, buraya bir yolu şudur:
import re
regex = re.compile(r"\<status\>(.*?)\</status\>", re.IGNORECASE)
s = """This is some long random text <status>This is the first status block</status>
and some more text <status>and another block</status>
and yet more <status>This is the last status block</status>"""
print(re.findall(regex, s))
verimleri
['This is the first status block', 'and another block', 'This is the last status block']
Bu yöntemin en önemli avantajı, bir çizgi üzerinde tüm<status>...</status>
blok değil, sadece ilk özler olmasıdır. Üç tırnak işaretli dizeler için, <status>
ve </status>
'un aynı satırda olması gerektiğini unutmayın.
Durumdaki metinde ne yapmak istersiniz? – Sarcoma
@sarcoma Kişisel kullanım için içine rastgele bir çizgi yazdırmak istiyorum –
Sorunuzu bunu yansıtmak için güncellemelisiniz. – Sarcoma