2

I'm looking to extract the extract the values of a particular attribute from a particular element, using Python 3.

An example of the element in question (Atom3d):

<Atom3d ID="18" Mapping="43" Parent="2" Name="C7" 
XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39" 
TemperatureType="Isotropic" IsotropicTemperature="0.0677" 
AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/>

I need to extract the XYZ value, and further need to take this value and separate the comma-separated numbers within it. I need to use these numbers in another input file of a different format, so I was thinking to assign them to three separate variables and take it from there.

I'm very inexperienced with Python, and completely so when it comes to XML. I'm not sure of which libraries I would need to use, if such libraries even exist and how to use them if they do.

1 Answer 1

1

http://docs.python.org/3/library/xml.etree.elementtree.html

>>> from xml.etree import ElementTree as ET
>>> elem = ET.fromstring('''<Atom3d ID="18" Mapping="43" Parent="2" Name="C7"
... XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39"
... TemperatureType="Isotropic" IsotropicTemperature="0.0677"
... AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/>
... ''')

get attribute using get('attribute-name'):

>>> elem.get('XYZ')
'0.0148299997672439,0.283699989318848,1.0291999578476'

split string by ',':

>>> elem.get('XYZ').split(',')
['0.0148299997672439', '0.283699989318848', '1.0291999578476']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.