Using a tree in python to get values
Question: So I am trying to create a Tree using Python to be able to try and read a text
file, which has repeating quantities within the file, and try to create a tree
out of these values and return the sentences with the Top 3 values (Explained
in more detail below).

First of all I searched on
[wikipedia](http://en.wikipedia.org/wiki/Tree_%28data_structure%29) on how a
tree is created and have also seen previous examples on stackoverflow like:
[This one](http://stackoverflow.com/questions/9499782/how-do-i-classify-this-
value-using-a-decision-tree). and [This
one](http://stackoverflow.com/questions/2824232/getting-a-tables-values-into-
a-tree). However I have only been able to do this so far as code goes:

    
    
    import fileinput
    
    setPhrasesTree = 0
    
    
    class Branch():
        def __init__(self, value):
            self.left = None
            self.right = None
            self.value = value
    
    class Tree():
        def __init__(self):
            self.root = None
            self.found = False
    
        #lessThan function needed to compare strings
        def lessThan(self, a, b):    
            if len(a) < len(b):
                loopCount = len(a)
            else:
                loopCount = len(b)        
            for pos in range(0, loopCount):
                if a[pos] > b[pos]:
                    return False        
            return True
    
        def insert(self, value):
            self.root = self.insertAtBranch(self.root, value)
    
        def exists(self, value):
            #set the class variable found to False to assume it is not there      
            self.found = False
            self.findAtBranch(self.root, value)
            return self.found
    
        #Used to fine a value in a tree
        def findAtBranch(self, branch, value):        
            if branch == None:
                pass
            else:
                if branch.value == value:
                    self.found = True                
                else:
                    self.findAtBranch(branch.left, value)
                    self.findAtBranch(branch.right, value)        
    
        def insertAtBranch(self, branch, value):
            if branch == None:
                return Branch(value)
            else:
                if self.lessThan(branch.value, value):
                    branch.right = self.insertAtBranch(branch.right, value)            
                else:
                    branch.left = self.insertAtBranch(branch.left, value)
                return branch
    
    def loadTree(filename, treeType):
    
        if treeType == setPhrasesTree:
            for sentence in fileinput.input("setPhrases.txt"):
                print(sentence)
                setPhrases.insert(sentence[:-1])
    
    
    def findSentenceType(sentence):
    
        if sentence.exists(sentence):
            return setPhrasesTree
    

Here is what text file looks like. Bare in mind that it is purposefully laid
out like this and not with a quantity value next to it (file name =
setPhrases.txt):

    
    
    Hi my name is Dave.
    Thank-You.
    What is your name?
    I have done all my homework.
    What time is dinner?
    What is your name?
    Thank-You.
    Hi my name is Dave.
    What is your name?
    I have done all my homework.
    What is your name?
    Can you bring me a drink Please?
    Can you bring me a drink Please?
    What is your name?
    Hi my name is Dave.
    What is your name?
    Can you bring me a drink Please?
    

Here is what I am trying to get my code to do. I need it to recognize that the
first sentence, in the file, is the starting node. And then it needs to tally
up all the other sentences that are the same and add a value to that sentence
and just use the tree to be able to do this. (I have originally done this in
another way, however I need to use a tree to be able to tally up and do all
the other stuff) Here is what I mean: ![enter image description
here](http://i.stack.imgur.com/dYpYc.png)

I then want to be able to return the top 3 `Phrases` with the highest
frequencies. So in this case the system would return the sentences (in this
order):

    
    
    What is your name?
    Hi my name is Dave.
    Can you bring me a drink please?
    

Any help is much appreciated. Also thank-you for your time.


Answer: Here you go, an implementation using a dictionary. Is this what you want?

    
    
    import collections
    def count_lines():
        d = collections.defaultdict(int)
        for line in open( "phrases.txt" ):
            d[ line.strip() ] += 1
    
        # we use the negative count as sort key, so the biggest ends up first
        a = sorted( d.items(), key=lambda x : -x[1] )
        for n, u in enumerate( a[:3] ):
            print( u[0], "# count=", u[1] )
    
    count_lines()        
    

