Answer the question
In order to leave comments, you need to log in
How to concisely rewrite code in python?
text to be parsed:
from pyparsing import *
texta = '''<RDF:RDF xmlns:NS1="http://amb.vis.ne.jp/mozilla/scrapbook-rdf#"
xmlns:NC="http://home.netscape.com/NC-rdf#"
xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<RDF:Description RDF:about="urn:scrapbook:item20200711150730"
NS1:id="20200711150730"
NS1:create="20200711150730"
NS1:title="Делаем из Vim-а конфетку / Хабр"
NS1:chars="UTF-8"
NS1:source="https://habr.com/ru/post/468265/"
NS1:comment=""
NS1:lock=""
NS1:type=""
NS1:icon="resource://scrapbook/data/20200711150730/favicon-16x16.png"
NS1:modify="20200711150804" />
<RDF:Seq RDF:about="urn:scrapbook:item20200704081851">
<RDF:li RDF:resource="urn:scrapbook:item20200704081900"/>
<RDF:li RDF:resource="urn:scrapbook:item20200711150730"/>
</RDF:Seq>'''
ns_id_p = Literal("NS1:id=")
pars = ns_id_p + Suppress('"') + Word(nums) + Suppress('"')
xx = pars.searchString(texta)
xxx = xx[0]
yyy = xxx[1]
print('xx ', xx)
print('xxx ', xxx)
print('yyy ', yyy)
xx
xxx ['NS1:id=', '20200711150730']
yyy 20200711150730
Answer the question
In order to leave comments, you need to log in
Conciseness should not be an end in itself. And then, what do you mean - "succinctly"? Fewer lines of code? Less characters?
You can write - if the question is "how to get the value of yyy" - like this:
print('yyy ', (Literal("NS1:id=") + Suppress('"') + Word(nums) + Suppress('"')).searchString(texta)[0][1])
Looking what task and what restrictions. If you're just looking for strings like
NS1:id="numbers",
then regular expressions will do. For example, re.compile('NS1:id="(\d+)"').
But if you then need to work with the structure of the xml document, then you need to use lxml.ElementTree.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question