-5

Can somebody teach me how to make a Python trie with continuation classes?

Implement a trie (letter tree) with continuation classes to represent the regular verbal paradigm of French (regular verbs ending in -er and -ir). The program is expected to analyze conjugated verb forms and to display the ininitive form and the grammatical description(s) of this form. For example, the conjugated verb form aimerais should yield the two following analyses:

aimerais ==> aimer / conditionnel 1ère personne singulier 

aimerais ==> aimer / conditionnel 2ème personne singulier

I have 3 files in the same folder. I don't know how I can search for the word and put it in a tree.

# TP 2 : TRIE WITH CONTINUATION CLASS

class Trie:

      def __init__(self, filename):
          self.__end = False
          self.__nodes = {}


      def myTrie (self, filename, encoding="utf8"):
          file = open(filename)
          trie = self._nodes(file.readlines())  
          for verbes in trie:
                  words = verbes[:-2]
                  trie_trie = trie_trie.setdefault(words,self._nodes)

          return trie_trie


      def myTrie_suffix_er (self, filename, encoding="utf8"):
          filesuffix_er = open(filename)
          suffix = self._nodes(filesuffix_er.readlines().split())
          suffix+="er"
          for a in range(len(suffix)):
              fin = self._nodes

              for b in suffix[a:]:
                  fin = fin[b]

      def myTrie_suffix_ir (self, filename, encoding="utf8"):
          filesuffix_ir = open(filename)
          suffix = self._nodes(filesuffix_ir.readlines().split())
          suffix+="ir"
          for c in range(len(suffix)):
              fin = self._nodes

              for d in suffix[c:]:
                  fin = fin[d]

ver = Trie ("suffixes-er.txt")
vir = Trie ("suffixes-er.txt")
print (ver)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • What is the content of your data file ? You say that you have no idea of what you're doing, but you are posting a entire class. Do you understand this class ? Did you write it ? Or it is a resource that a teacher let you complete to implement your program ? – Arthur Vaïsse Oct 15 '14 at 13:55
  • My friend and I are working on this. But even she has no idea of what we should do. We took the code on our handouts and also some online. Since its also our first time using Python. – iamchane Oct 15 '14 at 14:02
  • 3
    This is pretty complex for a first exercise - you should talk to whoever gave it to you about what you're already expected to know. – jonrsharpe Oct 15 '14 at 14:04
  • Ok take a look first at "http://fr.openclassrooms.com/informatique/cours/apprenez-a-programmer-en-python" (french version of the tutorial as you are interested in french) and to http://en.wikipedia.org/wiki/Trie . Then you should teel us what is in your 3 files. words with meaning ? words with information about such as infinite version of the word ? Clarify our need please. And @jonrsharpe +1 – Arthur Vaïsse Oct 15 '14 at 14:08
  • Actually I have 4 Files. First is for the verbes ending in ER, Second ending in IR. 3 and 4 are the Suffixes for verbes ending in ER, IR. The program must ask the user to input one word and then it should be able to tell which form it is in french. for example. If I will input "aimerais" it should have an output of aimer / conditionnel 1ère person singular. sorry my english is bad in explaining. – iamchane Oct 15 '14 at 14:10
  • I'll post you a stub program tomorow morning. – Arthur Vaïsse Oct 15 '14 at 14:42

1 Answers1

0

Here come a basic trie implementation with some comments to allow a better understanding of the code.

class Node():
    """ A tree's node """
    def __init__(self, value):
        self.value = value
        self.branchs = {}

    # method that start and end with "__" are magic method in python. They are used by many built in function and object
    # see at "http://www.rafekettler.com/magicmethods.html" for more information about them.
    def __repr__(self):
        """ Method called by print """
        subtrees = []
        for key in self.branchs.keys():
            subtrees.append(self.branchs[key].__repr__())

        return "({0}:{1})".format(self.value, ",".join(subtrees))

    def __contains__(self, word):
        """ Method called by 'in' """
        if word == []:
            return True
        else:
            key = word.pop(0)
            if key not in self.branchs.keys():
                return False
            else:
                return self.branchs[key].__contains__(word)

    def add(self, chain):
        """ Add a character chain in the tree. """
        if chain == []:
            pass
        else:
            #have to follow the branch that is labeled by the first letter of the chain.
            branch_key = chain[0]
            #extand the tree if needed
            if not branch_key in self.branchs.keys():
                self.branchs[branch_key] = Node(self.value + branch_key)
            #then recursivly call the add function
            self.branchs[branch_key].add(chain[1:])

# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-

class PrefixTree():
    """ A prefix tree object """

    def __init__(self):
        self.root = Node("")

    def insert(self, word):
        """ Insert a word in the tree """
        self.root.add(list(word))

    def __repr__(self):
        """ Method called by print """
        return "<PrefixTree : {0}>".format(self.root.__repr__())

    def __contains__(self, word):
        """ Method called by 'in' """
        return self.root.__contains__(list(word))

# -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*- -*-

#the main block of the program
if __name__ == "__main__" :

    words_1st_group = ["manger", "manquer", "rater", "roter", "rallier"]

    trie = PrefixTree()

    for word in words_1st_group :
        trie.insert(word)
        print(trie)

    print("'manger' is in trie :", 'manger' in trie)
    print("'Manger' is in trie :", 'Manger' in trie)

I believe that this code is more understandable by new being in the python universe than the one you got before. The code you were provided do not split the tree logic from the file parsing code for example that is a bad practice in general. The next step of this code would be to replace the hard codded list of words by the opening of a file and the add of every word it contains into the tree ( don't try to print it anymore then ;) ).

If any question regarding the code do not hesitate. If you do not succeed in asking something in English, I also speak French, so do not hesitate to contact me directly by email for answer.

Arthur Vaïsse
  • 1,551
  • 1
  • 13
  • 26