•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 456,596 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,423 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
Views: 724 | Replies: 5
![]() |
•
•
Join Date: Sep 2007
Posts: 10
Reputation:
Rep Power: 2
Solved Threads: 0
Alright, So I am rather new to programming and Python and I had a couple of questions that maybe you guys could help me with...
I currently have a .txt that when read in Python is a list, now i want to be able to split it up into seperate components so that i can put them all in a dictionary. I want to be able to up one part of the line and have it give me another part (obviously the purpose of having it as a dictionary).
a sample line from the file:
1 hydrogen H 1.0079
So if i were to say
>>>Print weight['Hydrogen']
1.0079
Here is a partial look at the code that I was attempting to write:
def make_atomic_weights_dict(data_lines):
d = {}
for data_line in data_lines:
parts = data_line.split()
d'[parts[3]] = float.parts [4]' # these will be added to dictionary
if len(parts) == 4:
print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])
Thanks a bunch
I currently have a .txt that when read in Python is a list, now i want to be able to split it up into seperate components so that i can put them all in a dictionary. I want to be able to up one part of the line and have it give me another part (obviously the purpose of having it as a dictionary).
a sample line from the file:
1 hydrogen H 1.0079
So if i were to say
>>>Print weight['Hydrogen']
1.0079
Here is a partial look at the code that I was attempting to write:
def make_atomic_weights_dict(data_lines):
d = {}
for data_line in data_lines:
parts = data_line.split()
d'[parts[3]] = float.parts [4]' # these will be added to dictionary
if len(parts) == 4:
print float.parts[4]
else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])
Thanks a bunch
•
•
Join Date: Dec 2006
Posts: 468
Reputation:
Rep Power: 2
Solved Threads: 65
•
•
•
•
1 hydrogen H 1.0079
if len(parts) == 4: print float.parts[4] else print 0 '%s does not have a well defined atomic weight.' % s(parts[3])
if len(parts)==4: print float(parts[3]) else : print "no atomic weight for %s" % (parts[1]) ## or try: a_weight = float(parts[3]) except: print "no atomic weight for %s" % (parts[1])
•
•
Join Date: Sep 2007
Posts: 10
Reputation:
Rep Power: 2
Solved Threads: 0
Alright, well I solved my previous problem...My next issue, is I want to be able to add up the numbers from the dictionary...how would I go about doing that?
So say I want to calculate the atomic mass of H2O I want to be able to type:
>>>print molecular_weight( 'H 2 O', atomic_weights)
some # comes out
I don't need a whole solution, just where would be a good place to start looking
So say I want to calculate the atomic mass of H2O I want to be able to type:
>>>print molecular_weight( 'H 2 O', atomic_weights)
some # comes out
I don't need a whole solution, just where would be a good place to start looking
•
•
Join Date: Jul 2006
Posts: 562
Reputation:
Rep Power: 4
Solved Threads: 72
Yeah, you're asking a parsing question: how do take a string representation of a chemical formula and represent it in memory?
I might do something like this, but there are smarter ways of doing it:
So some explanations:
* The constants defined at the beginning let me extract elements without using obscure indices that can cause trouble if I forget to count from zero.
* The problem with parsing a formula like H 2 O is that I have to remember one token back. 2 whats? Oh, yeah, 2 H's. That's the role that 'last' plays in the compute_mass function. It has the effect of creating a small pipeline: we get the current token, but compute the mass of the last token.
* Doing it like this REQUIRES that we not forget the tail end.
* Handling formulas like diethyl ether, (C 2 H 5) 2 O, requires a stack for handling parentheses. If you feel adventurous, you can probably do it.
* I used try...except and raise to handle errors. If that's weird to you, then skip it.
Jeff
I might do something like this, but there are smarter ways of doing it:
Python Syntax (Toggle Plain Text)
Z = 0 MASS = 1 NAME = 2 ELEMENTS = {'H': (1,1.00794,'hydrogen'), 'O': (8,15.9994,'oxygen'), 'C': (6,12.001, 'carbon'), 'N': (7,14.0064, 'nitrogen')} def get_mass(symbol): if symbol in ELEMENTS: return ELEMENTS[symbol][MASS] else: raise ValueError, "Element not in table!" def compute_mass(line): mass = 0.0 tokens = line.split() last = '' for token in tokens: # handle numbers if token.isdigit(): # correct input: number follows valid element if last: mass += get_mass(last) * int(token) last = '' # incorrect input: number follows nothing at all, or other number else: raise SyntaxError, "Illegal formula!" else: # if element follows other element, add last to mass if last: mass += get_mass(last) last = token # done with the line; don't forget the tail! if last: mass += get_mass(last) return mass while True: formula = raw_input("Enter a formula or 'quit': ") if formula.lower() == 'quit': break else: try: m = compute_mass(formula) print "mass is", m except StandardError, e: print e
So some explanations:
* The constants defined at the beginning let me extract elements without using obscure indices that can cause trouble if I forget to count from zero.
* The problem with parsing a formula like H 2 O is that I have to remember one token back. 2 whats? Oh, yeah, 2 H's. That's the role that 'last' plays in the compute_mass function. It has the effect of creating a small pipeline: we get the current token, but compute the mass of the last token.
* Doing it like this REQUIRES that we not forget the tail end.
* Handling formulas like diethyl ether, (C 2 H 5) 2 O, requires a stack for handling parentheses. If you feel adventurous, you can probably do it.
* I used try...except and raise to handle errors. If that's weird to you, then skip it.
Jeff
•
•
Join Date: Sep 2007
Posts: 10
Reputation:
Rep Power: 2
Solved Threads: 0
Ok, well I read what you gave me and I kind of put some stuff to work on my own...The beginning lines may not make sense because they relate to other parts of the code
def molecular_weight(formula, atomic_weights):
weights = []
formula_parts = formula.split()
for parts in formula_parts:
if parts in atomic_weights:
weights.append(atomic_weights.itervalues())
elif 0 in atomic_weights:
print '%s does not have well-defined atomic weight' % (formula_parts)
elif parts in formula_parts.isdigits(n): # isdigit doesn't seem to be a proper command what should I use instead....
weights[-1] *= n # I want to be able to append this to weights, but i get an syntax error when trying to use the .append function
return sum(weights)
![]() |
•
•
•
•
•
•
•
•
DaniWeb Python Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
api apple asm assembly x86 programming hla demo blogger blogging c c++ ccna cocoa code coding competition compiler compilers computer debugging developer development errors evaluation framework gdata google high-performance innovation java languages linerider mcse microsystems networking news next object online open oriented planning platform practices programming python rss software step steps sun tools tutorials xml
- PHP vs. ASP.NET for development platforms (PHP)
- ....> Graduation Project <..... (Computer Science and Software Design)
- suggestion needed (C++)
- Old School Compiler vs New Compiler (C++)
- Antivirus (Computer Science and Software Design)
- In over my head (C++)
- C++ is dying a slow death (C++)
- Simple Programming Errors (Computer Science and Software Design)
Other Threads in the Python Forum
- Previous Thread: tab-delimited data
- Next Thread: Good Python IDE


Linear Mode