python学习----字典
2017-11-10 本文已影响0人
橘颂betty
代码如下
# __author__ == 'xjiao'
# -*- coding:utf-8 -*-
import csv
def readTable(fileobj):
"""Read Periodic Table file into a dict.with element symbol as key."""
dataFile = csv.reader(fileobj)
periodicTable = {}
for row in dataFile:
#ignore header rows:elements begin with a number
if row[0].isdigit():
symbol = row[1]
periodicTable[symbol] = row[:8] #ignore end of row
return periodicTable
def parseElement(elementStr):
"""Parse element string into symbol and quantity.
e.e. Si2 return ('Si',s)"""
symbol = ""
quantity = ""
for ch in elementStr:
if ch.isalpha():
symbol = symbol + ch
else:
quantity = quantity + ch
if quantity == "":#if no number,default is 1
quantity = 1
return symbol,int(quantity)
#Read file
fileHandle = open('Periodic-Table.csv','rU')
#Create Dictionary of Periodic Table using element symbols as keys
periodicTable = readTable(fileHandle)
#Promot for input and convert compound into a list of element
compoundString = \
raw_input("Input a chemical compound,hyphenated,e.g. C-O2:")
compoundList = compoundString.split('-')
#Initialize atomic mass
mass = 0
print "The compound is composed of:",
#Parse comound list into symbol-quantity pairs,print name,and add mass
for c in compoundList:
symbol,quantity = parseElement(c)
print periodicTable[symbol][5], #print element name
mass = mass +quantity*float(periodicTable[symbol][6])
print "\n\nThe atomic mass of the compound is",mass
fileHandle.close()
输出结果如下:
D:\python\python.exe E:/python_project/Chapter8-3.py
Input a chemical compound,hyphenated,e.g. C-O2:H2-S-O4
The compound is composed of: hydrogen sulfur oxygen
The atomic mass of the compound is 98.086
Process finished with exit code 0