簡體   English   中英

從字典以特定格式打印值

[英]Printing values from dictionary in specific form

我有一本字典,其中包含與各種反應及其數據有關的鍵。 exponentn,評論等。我想搜索和打印有關原子'BR'的反應列表。 我的代碼當前以隨機順序打印“ BR”的所有反應和數據。 我不確定哪個數據對應於哪個反應。

我曾嘗試使用repr函數來輸出數據,如下所示,但運氣不佳:
reactionName:exponentn評論
我發現了另一個我想復制的問題,但未能做到。 從字典以特定格式(python)打印值和鍵

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 Reaction(object):
    def __init__(self, inputLine, sourceType=None):
        #self.reactionName = QVTorQPObject()
        self.exponentn = QVTorQPObject()
        self.comment = QVTorQPObject()
        self.readIn(inputLine, sourceType=sourceType)

        products, reactants = self.reactionName.split(">")
        self.products = [product.strip() for product in products.split("+")]
        self.reactants = [reactant.strip() for reactant in reactants.split("+")]


    def readIn(self, inputLine, sourceType=None):
        if sourceType == "echo": # Parsed reaction line for combined format

            echoPart           = inputLine.split("|")[0]    
            reactionName     = inputLine.split(":")[0].strip()
            exponentn        = echoPart.split("[")[1].split("]")[0].strip() # inputLine.split("[")[1].split("]")[0].strip()
            comment          = "%".join(echoPart.split("%")[1:]).strip() # "%".join(inputLine.split("%")[1:]).strip()

            # Store the objects
            self.reactionName = reactionName
            self.exponentn.echo = exponentn
            self.comment.echo = comment

        elif sourceType == "tv": # Parsed reaction line for combined format

            tvPart          = inputLine.split("|")[1]
            reactionName     = inputLine.split(":")[0].strip()
            comment          = "%".join(tvPart.split("!")[1:]).strip() # "%".join(inputLine.split("!")[1:]).strip()

            # Store the objects
            self.reactionName = reactionName
            self.comment.tv = comment


        elif sourceType.lower() == "unified":

            reaction = inputLine.split(":")[0]
            echoInput, tvInput = ":".join(inputLine.split(":")[1:]).split("|")

            echoInput = reaction + ":" + echoInput
            tvInput = reaction + ":" + tvInput

            if "Not present in TV" not in tvInput:
                self.readIn(inputLine, sourceType="tv")

            if "Not present in Echo" not in echoInput:
                self.readIn(inputLine, sourceType="echo")

        else:
            raise SourceNotDefinedException("'%s' is not a valid 'sourceType'" % sourceType) # Otherwise print

    def __repr__(self):
        return str({"reactionName": self.reactionName, "exponentn": self.exponentn, "comment": self.comment, })
        return str(self.reactionName) # Returns all relevant reactions


        keykeyDict = {}
        for key in reactionDict.keys():
            keykeyDict[key] = key

        formatString = "{reactionName:<40s} {comment:<10s}" # TV format
        formatString = "{reactionName:<40s} {exponentn:<10s} {comment:<10s}" # Echo format 
        return formatString.format(**keykeyDict)
        return formatString.format(**reactionDict)


    def toDict(self, priority="tv"):
        """Returns a dictionary of all the variables, in the form {"comment":<>, "exponentn":<>, ...}. 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, horrible, list comprehension, to avoid even more repeated text
            return dict([("reactionName", self.reactionName)] + [(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
               for attributeName in ["exponentn", "comment"]])

            else:
                raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print 

def find_allReactions(allReactions, reactant_set):
    """
    reactant_set is the set of reactants that you want to grab all reactions which are relevant allReactions is just the set of reactions you're considering. Need to repeatedly loop through all reactions. If the current reaction only contains reactants in the reactant_set, then add all its products to the reactant set. Repeat this until reactant_set does not get larger.
    """

    reactant_set = set(reactant_set) # this means that we can pass a list, but it will always be treated as a set.
    #Initialise the list of reactions that we'll eventually return
    relevant_reactions = []
    previous_reactant_count = None

    while len(reactant_set) != previous_reactant_count:
        previous_reactant_count = len(reactant_set)

    for reaction in allReactions:
        if set(reaction.reactants).issubset(reactant_set):
            relevant_reactions.append(reaction)
            reactant_set = reactant_set.union(set(reaction.products))

    return relevant_reactions

print find_allReactions(allReactions, ["BR"])

電流輸出:

'{'exponentn': {'tv': '0', 'echo': '0'}, 'comment': {'tv': 'BR-NOT USED', 'echo': 'BR-NOT USED'},'reactionName': 'E + BR > BR* + E', {'exponentn': {'qvt': '0', 'qp': '0'}, 'comment': {'qvt': 'BR+ -RECOMBINATION', 'qp': 'BR+ -RECOMBINATION'},'reactionName': 'E + BR* > BR* + E'

所需的輸出:
reactionName指數注釋
E + BR> BR * + E 0 BR +-重組

E + BR *> BR * + E 0不使用

如果您的數據按特定順序添加到字典中,並且您想要保留該順序,則需要使用collections.OrderedDict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM