目标是输入一种化学化合物,例如C6H12O6,并返回该化合物的原子量和化学名称。我想出了如何找到原子量的方法,但我想不出如何打印元素名称的方法。我将所有符号放在字典中作为键,值是一个元组,权重是第一个索引,名称是第二个。
我尝试过一个for循环,该循环将遍历列表的每个元素,然后将该元素替换为字典中的名称。
import re
def makeDictionary:()
mydict={}
inFile = open("atomic_weights.txt")
for line in inFile:
line = line.strip()
(weight,symbol,name) = line.split("\t")
mydict[symbol]=(float(weight),name)
return mydict
def splitCompound(mydict):
compound=input("Chemical composition?")
#this separates the symbols and the numbers in the compound
elements = re.findall('([A-Z][a-z]?)([0-9]*)',compound)
elementsUsed=[]
for i in elements:
myElement=i[0]
elementsUsed.append(myElement)
i=0
while i<len(elementsUsed):
names=mydict[myElement][1]
i+=1
print(elementsUsed)
print(names)
def main():
mydict = makeDictionary()
splitCompound(mydict)
main()
如果我输入“ H2O”,那么我的elementsUsed列表将打印:['H','O'],但我的姓名列表仅在我希望其打印['Hydrogen','Oxygen']时打印“ Oxygen”。 基本上,它只是用化学名称代替列表的最后一个元素,而不是我的elementsUsed列表中的每个元素。