我有一些化学品,数据库中有相应的数据,我如何通过其公式,例如o2,返回特定化学品及其数据。
class SourceNotDefinedException(Exception):
def __init__(self, message):
super(SourceNotDefinedException, self).__init__(message)
class tvorechoObject(object):
"""The class stores a pair of objects, "tv" objects, and "echo" objects. They are accessed
simply by doing .tv, or .echo. If it does not exist, it will fall back to the other variable.
If neither are present, it returns None."""
def __init__(self, echo=None, tv=None):
self.tv = tv
self.echo = echo
def __repr__(self):
return str({"echo": self.echo, "tv": self.tv}) # Returns the respective strings
def __getattribute__(self, item):
"""Altered __getattribute__() function to return the alternative of .echo / .tv if the requested
attribute is None."""
if item in ["echo", "tv"]:
if object.__getattribute__(self,"echo") is None: # Echo data not present
return object.__getattribute__(self,"tv") # Select TV data
elif object.__getattribute__(self,"tv") is None: # TV data not present
return object.__getattribute__(self,"echo") # Select Echo data
else:
return object.__getattribute__(self,item) # Return all data
else:
return object.__getattribute__(self,item) # Return all data
class Chemical(object):
def __init__(self, inputLine, sourceType=None):
self.chemicalName = TVorEchoObject()
self.mass = TVorEchoObject()
self.charge = TVorEchoObject()
self.readIn(inputLine, sourceType=sourceType)
def readIn(self, inputLine, sourceType=None):
if sourceType.lower() == "echo": # Parsed chemical line for Echo format
chemicalName = inputLine.split(":")[0].strip()
mass = inputLine.split(":")[1].split(";")[0].strip()
charge = inputLine.split(";")[1].split("]")[0].strip()
# Store the objects
self.chemicalName.echo = chemicalName
self.mass.echo = mass
self.charge.echo = charge
elif sourceType.lower() == "tv": # Parsed chemical line for TV format
chemicalName = inputLine.split(":")[0].strip()
charge = inputLine.split(":")[1].split(";")[0].strip()
mass = inputLine.split(";")[1].split("&")[0].strip()
# Store the objects
self.chemicalName.tv = chemicalName
self.charge.tv = charge
self.mass.tv = molecularWeight
else:
raise SourceNotDefinedException(sourceType + " is not a valid `sourceType`") # Otherwise print
def toDict(self, priority="echo"):
"""Returns a dictionary of all the variables, in the form {"mass":<>, "charge":<>, ...}.
Design used is to be passed into the Echo and TV style line format statements."""
if priority in ["echo", "tv"]:
# Creating the dictionary by a large, to avoid repeated text
return dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
for attributeName in ["chemicalName", "mass", "charge"]])
else:
raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print
from ParseClasses import Chemical
allChemical = []
chemicalFiles = ("/home/temp.txt")
for fileName in chemicalFiles:
with open(fileName) as sourceFile:
for line in sourceFile:
allChemical.append(Chemical(line, sourceType=sourceType))
for chemical in allChemical:
print chemical.chemicalName #Prints all chemicals and their data in list format
for chemical in allChemical(["o2"]):
print chemical.chemicalName
输出以下错误,我试图补救没有运气; TypeError:'list'对象不可调用
答案 0 :(得分:2)
问题是两行
for chemical in allChemical(["o2"]):
print chemical.chemicalName
allChemical
是一个列表,您不能只执行a_list()
。您似乎在尝试在列表中找到['o2']
或'o2'
。为此,您可以获取项目的索引,然后从列表中获取该索引。
allChemical[allChemical.index("o2")]
答案 1 :(得分:1)
在python中,列表对象是一个结构,用于保存其他对象,并为其包含的每个对象提供索引。像这样:
Index Object
0 "hello"
1 "world"
2 "spam"
如果要访问其中一个对象,则必须知道其索引:
objList[0] #returns "hello" string object
如果您不知道索引,可以使用index
方法找到它:
objList.index("hello") #returns 0
然后,您可以使用找到的索引将对象从列表中取出:
objList[objList.index("hello")]
然而,这有点愚蠢,因为你可以这样做:
"hello"
在这种情况下会产生相同的结果。
您的allChemical
对象是一个列表。看起来行chemicalFiles = ("/home/temp.txt")
正在用某种类型的对象填充您的列表。为了回答您的问题,您必须提供有关列表包含的对象的更多信息。我假设信息在您正在使用的ParseClasses
模块中。
如果您可以提供有关正在导入的Chemical
对象的更多信息,那么这可能有助于解决您的问题。
如果列表中包含的对象是str
的子类,则可以使用:
allChemical[allChemical.index("o2")].chemicalName
"02"
是一个str
对象,因此index
将在列表中查找str
对象(或str
的子对象)找到它的索引。但是,如果对象不是字符串,则无法找到它。
作为学习练习,试试这个:
class Chemical(str):
'''A class which is a subclass of string but has additional attributes such as chemicalName'''
def __init__(self,chemicalName):
self.chemicalName = chemicalName
someChemicals = [Chemical('o2'),Chemical('n2'),Chemical('h2')]
for chemical in someChemicals: print(chemical.chemicalName)
#prints all the chemical names
print(someChemicals[0].chemicalName)
#prints "o2"; notice you have to know the index ahead of time
print(someChemicals[someChemicals.index("o2")].chemicalName)
#prints "o2" again; this time index found it for you, but
#you already knew the object ahead of time anyway, sot it's a little silly
这很有效,因为索引能够找到您要查找的内容。如果它不是一个字符串就找不到它,如果你不知道索引'o2'是什么,如果你想获得你化学品列表中的特定化学品,你将需要详细了解这些对象。
答案 2 :(得分:1)
尝试此功能:
def chemByString(chemName,chemicals,priority="echo"):
for chemical in chemicals:
chemDict = chemical.toDict(priority)
if chemDict["chemicalName"] == chemName
return chemical
return None
此函数使用toDict()
类中的Chemical
方法。您从Chemical
类粘贴的代码解释了此方法从化学对象返回字典:
def toDict(self, priority="echo"):
"""Returns a dictionary of all the variables, in the form {"mass":<>, "charge":<>, ...}.
Design used is to be passed into the Echo and TV style line format statements."""
if priority in ["echo", "tv"]:
# Creating the dictionary by a large, to avoid repeated text
return dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
for attributeName in ["chemicalName", "mass", "charge"]])
else:
raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print
这本词典看起来像这样:
"chemicalName" : <the chemical name>
"mass" : <the mass>
"charge" : <the charge>
我上面创建的函数是迭代列表中的所有化学物质,找到名称等于&#34; o2&#34;的第一个,并返回该化学物质。以下是如何使用它:
chemByString("o2",allChemicals).chemicalName
如果上述方法不起作用,可能想尝试使用备用优先级(&#34; tv&#34;),但我不确定这是否会产生任何影响:
chemByString("o2",allChemicals,"tv").chemicalName
如果找不到化学品,该函数将返回None
:
chemByString("myPretendChemical",allChemicals).chemicalName