当前位置: 首页>>代码示例>>Python>>正文


Python Tree.get_node方法代码示例

本文整理汇总了Python中treelib.Tree.get_node方法的典型用法代码示例。如果您正苦于以下问题:Python Tree.get_node方法的具体用法?Python Tree.get_node怎么用?Python Tree.get_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在treelib.Tree的用法示例。


在下文中一共展示了Tree.get_node方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: AcquisitionChain

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
class AcquisitionChain(object):
    def __init__(self):
        self._tree = Tree()
        self._root_node = self._tree.create_node("acquisition chain", "root")
        self._device_to_node = dict()

    def add(self, master, slave):
        slave_node = self._tree.get_node(slave)
        master_node = self._tree.get_node(master)
        if slave_node is not None and isinstance(slave, AcquisitionDevice):
            if slave_node.bpointer is not self._root_node and master_node is not slave_node.bpointer:
                raise RuntimeError(
                    "Cannot add acquisition device %s to multiple masters, current master is %s"
                    % (slave, slave_node._bpointer)
                )
            else:  # user error, multiple add, ignore for now
                return

        if master_node is None:
            master_node = self._tree.create_node(tag=master.name, identifier=master, parent="root")
        if slave_node is None:
            slave_node = self._tree.create_node(tag=slave.name, identifier=slave, parent=master)
        else:
            self._tree.move_node(slave_node, master_node)

    def _execute(self, func_name):
        tasks = list()

        prev_level = None
        for dev in reversed(list(self._tree.expand_tree(mode=Tree.WIDTH))[1:]):
            node = self._tree.get_node(dev)
            level = self._tree.depth(node)
            if prev_level != level:
                gevent.joinall(tasks)
                tasks = list()
            func = getattr(dev, func_name)
            tasks.append(gevent.spawn(func))
        gevent.joinall(tasks)

    def prepare(self, dm, scan_info):
        # self._devices_tree = self._get_devices_tree()
        for master in (x for x in self._tree.expand_tree() if isinstance(x, AcquisitionMaster)):
            del master.slaves[:]
            for dev in self._tree.get_node(master).fpointer:
                master.slaves.append(dev)

        dm_prepare_task = gevent.spawn(dm.prepare, scan_info, self._tree)

        self._execute("_prepare")

        dm_prepare_task.join()

    def start(self):
        self._execute("_start")
        for acq_dev in (x for x in self._tree.expand_tree() if isinstance(x, AcquisitionDevice)):
            acq_dev.wait_reading()
            dispatcher.send("end", acq_dev)
开发者ID:mguijarr,项目名称:bliss,代码行数:59,代码来源:continuous_scan.py

示例2: test_modify_node_identifier_directly_failed

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
    def test_modify_node_identifier_directly_failed(self):
        tree = Tree()
        tree.create_node("Harry", "harry")
        tree.create_node("Jane", "jane", parent="harry")
        n = tree.get_node("jane")
        self.assertTrue(n.identifier == 'jane')

        # Failed to modify
        n.identifier = "xyz"
        self.assertTrue(tree.get_node("xyz") is None)
        self.assertTrue(tree.get_node("jane").identifier == 'xyz')
开发者ID:caesar0301,项目名称:treelib,代码行数:13,代码来源:test_tree.py

示例3: test_modify_node_identifier_recursively

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
    def test_modify_node_identifier_recursively(self):
        tree = Tree()
        tree.create_node("Harry", "harry")
        tree.create_node("Jane", "jane", parent="harry")
        n = tree.get_node("jane")
        self.assertTrue(n.identifier == 'jane')

        # Success to modify
        tree.update_node(n.identifier, identifier='xyz')
        self.assertTrue(tree.get_node("jane") is None)
        self.assertTrue(tree.get_node("xyz").identifier == 'xyz')
开发者ID:caesar0301,项目名称:treelib,代码行数:13,代码来源:test_tree.py

示例4: AcquisitionChain

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
class AcquisitionChain(object):
    def __init__(self, parallel_prepare=False):
        self._tree = Tree()
        self._root_node = self._tree.create_node("acquisition chain", "root")
        self._device_to_node = dict()
        self._presets_list = list()
        self._parallel_prepare = parallel_prepare
        self._device2one_shot_flag = weakref.WeakKeyDictionary()

    @property
    def nodes_list(self):
        nodes_gen = self._tree.expand_tree()
        nodes_gen.next()  # first node is 'root'
        return list(nodes_gen)

    def add(self, master, slave):
        self._device2one_shot_flag.setdefault(slave, False)

        slave_node = self._tree.get_node(slave)
        master_node = self._tree.get_node(master)
        if slave_node is not None and isinstance(slave, AcquisitionDevice):
            if(slave_node.bpointer is not self._root_node and
               master_node is not slave_node.bpointer):
                raise RuntimeError("Cannot add acquisition device %s to multiple masters, current master is %s" % (
                    slave, slave_node._bpointer))
            else:                 # user error, multiple add, ignore for now
                return

        if master_node is None:
            master_node = self._tree.create_node(
                tag=master.name, identifier=master, parent="root")
        if slave_node is None:
            slave_node = self._tree.create_node(
                tag=slave.name, identifier=slave, parent=master)
        else:
            self._tree.move_node(slave, master)
        slave.parent = master

    def add_preset(self, preset):
        self._presets_list.append(preset)

    def set_stopper(self, device, stop_flag):
        """
        By default any top master device will stop the scan.
        In case of several top master, you can define which one won't
        stop the scan
        """
        self._device2one_shot_flag[device] = not stop_flag

    def __iter__(self):
        if len(self._tree) > 1:
            return AcquisitionChainIter(self, parallel_prepare=self._parallel_prepare)
        else:
            return iter(())
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:56,代码来源:chain.py

示例5: print_prob_val

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
 def print_prob_val(self, fname="OutTree.txt"):
     n_tree = Tree(tree=self.tree)
     for node in n_tree.nodes:
         node = n_tree.get_node(node)
         node.tag = "{tag} - {val} - {prob}".format(tag=node.tag, val=node.data[0], prob=node.data[1])
     n_tree.save2file(fname)
     self.tree =  None
开发者ID:tomgond,项目名称:snipplets,代码行数:9,代码来源:lz78.py

示例6: build_header_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
    def build_header_tree(self):
        header_tree = Tree()

        root_field = ReportDefinitionField()
        root_field.alias = 'root'
        root_field.header = 'Root'
        root_field.sub_fields = self.report_definition.fields

        self.__build_header_tree(header_tree, None, root_field)
        self.__prepare_header_data(header_tree, header_tree.get_node(header_tree.root))

        return header_tree
开发者ID:adam1978828,项目名称:webapp1,代码行数:14,代码来源:base.py

示例7: retrieve_dependencies

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
    def retrieve_dependencies(self, jarName):
        if jarName is None:
            root = self.tree.get_node(self.tree.root)
            root = root.data.jarName
        else:
            root = jarName

        tgfOutput = subprocess.Popen('dosocs2 dependencies ' + root, stdout=subprocess.PIPE, shell=True)
        count = 0
        tree = Tree()
        dependencies = []
        relationships = []
        while True:
            line = tgfOutput.stdout.readline()

            if not line:
                break

            match = re.match(r"(\d+) - (.*)", line)
            if match:
                if count == 0:
                    count = count + 1
                    tree.create_node(match.group(2), match.group(1))
                else:
                    dependencies.append((match.group(2), match.group(1)))

            match = re.match(r"(\d+) (\d+)", line)

            if match:
                relationships.append((match.group(1), match.group(2)))

        if not relationships:
            print("No child relationships for " + jarName)
            return None

        while relationships:
            for item in relationships:
                node = tree.get_node(item[0])

                if node is not None:
                    rel = [item for item in relationships if int(item[0]) == int(node.identifier)]
                    if rel is not None:
                        rel = rel[0]
                        dep = [item for item in dependencies if int(item[1]) == int(rel[1])]
                        if dep is not None:
                            dep = dep[0]
                            tree.create_node(dep[0], dep[1], parent=node.identifier)
                            relationships.remove(rel)
                            dependencies.remove(dep)

        tree.show()
        if jarName is None:
            os.chdir(os.pardir)
开发者ID:pombredanne,项目名称:CSCI4900,代码行数:55,代码来源:dependency_reader.py

示例8: StateMachine

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
class StateMachine(object):
    """A class to track information about a state machine"""

    def __init__(self, name):
        self.name = name
        self.events = {}
        self.effects = {}
        self.state_tree = Tree()
        self.current_state = None

        # Add the Root state automatically
        self.add_state('Root')

    def add_state(self, name):
        assert isinstance(name, str)
        state_node = Node(identifier=name, data=State(name))

        if self.current_state is None:
            self.state_tree.add_node(state_node)
            self.current_state = state_node.data
        else:
            self.state_tree.add_node(state_node, self.current_state.name)

    def add_event(self, ev):
        assert isinstance(ev, Event)
        self.events[ev.name] = ev

    def add_effect(self, eff):
        assert isinstance(eff, Effect)
        self.effects[eff.name] = eff

    def enter_state(self, state):
        self.current_state = state

    def exit_state(self, state):
        self.current_state = self.state_tree.parent(state.name).data

    def get_state_by_name(self, state_name):
        return self.state_tree.get_node(state_name).data
开发者ID:r-chaves,项目名称:plantuml-codegen,代码行数:41,代码来源:sm_entities.py

示例9: iiif_recurse

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
def iiif_recurse(uri, tr=None, parent_nid=None,
                 separator='/', parent_type=None):
    '''
    Treelib nodes have a tag (human readable), and a nid (node id).

    Sanitised uris are used in the nids, throughout, concatenated
    with the parent id, with a separator, so the path segments can
    be recreated.

    Comments: Nid and denid adds an extra level of list handling, as it joins
    and the splits. Might be better to create the path (no processing)
    and then create the nid.
    '''
    try:
        print 'URI: %s' % uri
        obj = IIIF_Object(uri)
        if not tr:
            tr = Tree()
        if parent_nid:
            root_nid = separator.join([parent_nid, sanitise_uri(uri)])
            if parent_type:
                obj.data['parent_type'] = parent_type
            if not tr.get_node(root_nid):
                tr.create_node(uri, root_nid, parent=parent_nid, data=obj.data)
        else:
            root_nid = sanitise_uri(uri)
            tr.create_node(uri, root_nid, data=obj.data)
        recursion_lists = [
            'members', 'collections', 'manifests', 'sequences', 'canvases']
        dereferenceable = ['sc:Collection', 'sc:Manifest']
        if obj.source_dict:
            dict_parse(obj.source_dict, root_nid, tr, separator,
                       recursion_lists, dereferenceable)
    except:
        raise
    return tr
开发者ID:CultureStack,项目名称:IIIF_Discovery,代码行数:38,代码来源:iiif_tree_members.py

示例10: Tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
print nt_start

tree = Tree()
tree.create_node("S", nt_start)
tree.create_node("NP", nt_start+1, parent=nt_start)
tree.create_node("VP", nt_start+2, parent=nt_start)

tree.create_node("Jeg", s.index("Jeg"), parent=4)
tree.create_node("er", s.index("er"), parent=5)
tree.create_node("glad", s.index("glad"), parent=5)

tree.show()

searchword = "glad"
wid = s.index(searchword)
node = tree.get_node(wid)

print




entity = "er"
opinionw = "glad"


# Find lowest common ancestor

def get_LCA(root, n1, n2):
	if root is None: return None
	if root == n1 or root == n2: return root
开发者ID:ninaholm,项目名称:Discourse-Machine,代码行数:33,代码来源:tree_tester.py

示例11: SentenceTree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]

#.........这里部分代码省略.........

				# Create left child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(left_child[0], cid, parent=pid)
				if left_child[2] is None: #If left_child is a leaf node, append a word node
					nid = left_coord[1]-1
					word = self.matrix[left_coord[0]-1][left_coord[1]][0]
					word = word.decode('utf-8', "ignore")
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(left_child, cid) # Create children of left_child

				# Create right child as node (plus extra word node if leaf)
				cid = self._nnid()
				self.tree.create_node(right_child[0], cid, parent=pid)
				if right_child[2] is None: #If right_child is a leaf node, append a word node
					nid = right_coord[1]-1
					word = self.matrix[right_coord[0]-1][right_coord[1]][0]
					word = word.decode('utf-8', "ignore")
					self.tree.create_node(word, nid, parent=cid)
				else:
					self._create_children(right_child, cid) # Create children of right_child



	# Returns the sentence's sentiment score
	def get_sentiment_score(self, sentimentDict, term):
		total_score = 0

		# negation dictionary
		negationList = ["ikke", "ej"]

		# Check the term against every sentiment word
		n1 = self.sentence.index(term)
		for word in sentimentDict:
			if term==word: continue # If topic term is an opinion word, ignore.
			n2 = self._in_sentence(word)
			if n2 is not False:
				d = self._get_distance(n1, n2)
				if d == 0: score = float(sentimentDict[word])
				score = float(sentimentDict[word]) / float(d)

				# If SentWord is negated, flip the score derived from it
				if self._is_negated(word, negationList):
					score = score * -1

				print "Term: %s | SentWord: %s | Distance: %s | Score: %s" % (term, word, d,score)
				total_score += score

		print "Total score:", total_score
		return total_score


	# Checks whether a word is within a specified threshold distance of a negation word
	def _is_negated(self, w, negationList):
		negationThreshold = 3
		n1 = self._in_sentence(w)
		if n1 is None: return False
		for nw in negationList:
			n2 = self._in_sentence(nw)
			if n2 is not None:
				if (self._get_distance(n1, n2)) < negationThreshold:
					print "negating word", w
					return True
		return False


	# Checks whether word w exists in the ST's sentence
	def _in_sentence(self, w):
		if w in self.sentence:
			return self.sentence.index(w)
		return False


	# Returns distance between two nodes n1 and n2
	def _get_distance(self, n1, n2):
		LCA = self._get_LCA(self.tree.root, n1, n2)
		distance = self.tree.depth(self.tree.get_node(n1)) + self.tree.depth(self.tree.get_node(n2))
		distance = distance - 2 * self.tree.depth(self.tree.get_node(LCA))
		return abs(distance)


	# Returns lowest common ancestor of two nodes n1 and n2
	# Supporting method of _get_distance()
	def _get_LCA(self, current_node, n1, n2):
		if current_node is None: return None
		if current_node == n1 or current_node == n2: return current_node
		if len(self.tree.get_node(current_node).fpointer) == 0: return None #if leaf, return None
		if len(self.tree.get_node(current_node).fpointer) == 1: #if terminal node, check its single leaf node
			return self._get_LCA(self.tree.get_node(current_node).fpointer[0], n1, n2)

		if len(self.tree.get_node(current_node).fpointer) == 2:
			left = self._get_LCA(self.tree.get_node(current_node).fpointer[0],n1,n2)
			right = self._get_LCA(self.tree.get_node(current_node).fpointer[1],n1,n2)

		if left is not None and right is not None: return current_node
		if left is not None: return left
		if right is not None:return right

		return None
开发者ID:ninaholm,项目名称:Discourse-Machine,代码行数:104,代码来源:SentenceTree.py

示例12: WikipediaResolver

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
class WikipediaResolver(object):
    """ WikipediaResolver class
    """
    _base_wiki_url = 'https://pl.wikipedia.org'
    _base_wiki_url_search = _base_wiki_url + '/wiki/'

    def __init__(self, start_from, finish_at):
        """
        :param start_from: Wikipedia entry like "Chrześcijaństwo"
        :param finish_at: Wikipedia entry like "Biblia"
        :return: WikipediaResolver instance
        """
        self._tree = Tree()
        self._finish_at_url = requests.get(self._base_wiki_url_search + finish_at).url
        self._to_check_list = [(None, self._base_wiki_url_search + start_from)]
        self._known_resources = set()

    def solve(self):
        """
        :return: returns ordered list (start point first) of found links (steps)
        """
        while True:
            found_node = self._process_level()
            if found_node:
                break

        # logging.debug("Formating tree... This may take a while.")
        # self._show_tree()

        path = self._backtrack_path()

        return path

    def _process_level(self):
        """
        :return: Bool. True if target link was found in dispached breadth graph search iteration, else False
        """
        to_check_list = []
        while self._to_check_list:
            parent_url, url = self._to_check_list.pop(0)
            self._known_resources.add(url)

            if not parent_url:
                self._tree.create_node(url, url)  # this is root node

            set_to_check = set((self._base_wiki_url + a.attr('href') for a in self._get_a_items(requests.get(url).text) if a.attr('href')))

            set_to_check -= self._known_resources

            map((lambda _url: self._tree.create_node(_url, _url, parent=url)), set_to_check)

            if self._finish_at_url in set_to_check:
                return True

            to_check_list += [(url, _url) for _url in set_to_check]
            self._known_resources.update(set_to_check)

        self._to_check_list += to_check_list

    def _show_tree(self):
        """ This simply print current state of the tree
        :return: Nothing
        """
        self._tree.show()

    def _backtrack_path(self):
        """ Backtracks found link among the tree.
        :return: returns ordered list (start point first) of found links (steps)
        """
        node = self._tree.get_node(self._finish_at_url)
        nodes = [node]

        while node.bpointer:
            nodes.append(self._tree.get_node(node.bpointer))
            node = self._tree.get_node(node.bpointer)

        return list(reversed([node.identifier for node in nodes]))

    @staticmethod
    def _get_a_items(html):
        dom = PQ(html)  # this parses html into tree
        return dom.find('a[href^="/wiki/"]:not([href*=":"])').items()  # Neat jquery style selectors. #PDK
开发者ID:diego351,项目名称:wikiparser,代码行数:84,代码来源:wikipediaresolver.py

示例13: range

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
for i in range(0,len(etiquetas)-1):
	entropias.append(calEntropia(contenido,i))
menorColumna=buscarMenor(entropias)

tree=Tree()
tree.create_node({"Etiqueta":etiquetas[menorColumna] , "Camino": "Raiz", "CamElg":0},0)




historicoContenido = []
historicoEtiquetas =[]



hijo=tree.get_node(0)
histFunc=[]
histFunc.append(contenido)
histHij=[]
histHij.append(hijo)
hisEtiq=[]
hisEtiq.append(etiquetas)
hijosRaiz=0

ide=1
print UnaPos(contenido,"0",3)
while(hijosRaiz<=len(valoresResultados)):
	aaa = raw_input("")
	print ("------------------")
	tree.show()
	if(len(hijo._fpointer)<valoresResultados and len(contenido)>2):
开发者ID:r041292,项目名称:DT-Entropy-Zurek,代码行数:33,代码来源:DT+-+copia.py

示例14: verifier

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]

#.........这里部分代码省略.........
    
    def assignAtom(self, i):
        for atomEquivClass in self.SameAtomList.get_sets():
            if str(i) in atomEquivClass:
                return self.SameAtomList.get_leader(str(i))
            
        self.SameAtomList.insert(str(i))
        return self.SameAtomList.get_leader(str(i))
            
    def setUpSameAtomList(self):
        '''
        Using the Union Find datastructure, I will keep track of the equivalence
        classes of SameAtoms and then supply a label based on the index of the
        subset in which a subformula corresponding with an atom is contained.
        '''
        
        startIndexSameAtoms = findInFile(self.instanceFileLines, lambda x: "PREDICATE SameAtom" in x) + 1
        sameAtomPairs = self.instanceFileLines[startIndexSameAtoms:]
        
        for pair in sameAtomPairs:
            tmp = pair.split(",")
            label1 = tmp[0].split("(")[1]
            label2 = tmp[1].split(")")[0]
            self.SameAtomList.insert(label1, label2)
            
    def determineConnective(self, i):
        '''
        Each subformula label is guaranteed to be the first argument of some
        tuple; either it will correspond with an atom, the only argument,
        or it will correspond with the main connective of a unary 
        (i.e. negation, box, or diamond) or binary (i.e. conjunction or 
        disjunction) subformula.
        '''
        SiThing=findInFile(self.instanceFileLines, lambda x: "("+str(i)+")" in x)
        if SiThing:
            for k in range(SiThing, 0, -1): # go back in the file until you can find out what predicate we're dealing with
                if self.instanceFileLines[k].split(" ")[0] == "PREDICATE":
                    if self.instanceFileLines[k].split(" ")[1] == "Falsum":
                        return "false"
            return self.assignAtom(i)
        if findInFile(self.instanceFileLines, lambda x: "("+str(i)+"," in x):
            SiAsMainConnective = findInFile(self.instanceFileLines, lambda x: "("+str(i)+"," in x)
            for j in range(SiAsMainConnective, 0, -1): # go back in the file until you can find out what predicate we're dealing with
                if self.instanceFileLines[j].split(" ")[0] == "PREDICATE":
                    if self.instanceFileLines[j].split(" ")[1] == "SameAtom": # if there are no tuples under SameAtom, then this isn't reached due to SiAsMainConnective
                        return self.assignAtom(i)
                    else:
                        return self.assignSymbol(self.instanceFileLines[j].split(" ")[1]) # if the predicate refers to an operator, then we need to find out which one!
    
    def nodeCreation(self, predicate, SiConnective, i):        
        SiAsOperand = findInFile(self.instanceFileLines, predicate)
        ParentOfSi = str(self.instanceFileLines[SiAsOperand].split(",")[0].split("(")[1])
        self.syntaxTree.create_node(SiConnective, str(i), parent=ParentOfSi)        
        
    def makeSyntaxTreeNode(self, SiConnective, i):  
        if findInFile(self.instanceFileLines, lambda x: ","+str(i)+"," in x): #find where subformula i appears as second operand, and 
            self.nodeCreation(lambda x: ","+str(i)+"," in x, SiConnective, i)
        elif findInFile(self.instanceFileLines, lambda x: ","+str(i)+")" in x):                   
            self.nodeCreation(lambda x: ","+str(i)+")" in x, SiConnective, i) 
        else:
            self.syntaxTree.create_node(SiConnective,str(i))
                
    def buildTree(self):
        '''
        To build the syntax tree for the formula as laid out in the instance
        file, we need to delve into the formula by means of stripping off the
        main connective of each subformula (starting with the main connective
        of the formula itself) and labeling a tree node with the symbol
        corresponding with that connective. Note that each subformula appears
        exactly once as the first argument of a tuple, and can appear at most
        once as a second (or third, for binary operators) argument in a tuple.             
        '''
        self.syntaxTree = Tree()
        for i in range(1, self.numTreeNodes+1):
            SiConnective = self.determineConnective(i)
            self.makeSyntaxTreeNode(SiConnective, i)
          
    def myShowTree(self, tree, root):
        '''
        In-order depth-first traversal of syntax tree using deep recursion; first
        layer of recursion receives root of tree, where each sub-layer receives
        respectively the left child then the right child as roots of those subtrees
        with visitation of the root node occurring in the middle.
        '''
        rootNID = root.identifier
        x=self.syntaxTree.children(rootNID)
        
        if len(self.syntaxTree.children(rootNID)) == 2:
            print("(", end=" ")
            self.myShowTree(self.syntaxTree, self.syntaxTree.children(rootNID)[0])
            
        print(self.syntaxTree.get_node(rootNID).tag, end=" ")
        
        if len(self.syntaxTree.children(rootNID)) >= 1:
            if len(self.syntaxTree.children(rootNID)) == 1:
                print("(", end=" ")
                self.myShowTree(self.syntaxTree, self.syntaxTree.children(rootNID)[0])
            else:
                self.myShowTree(self.syntaxTree, self.syntaxTree.children(rootNID)[1])
            print(")", end=" ")   
开发者ID:wandaboyer,项目名称:modalSolverSuite,代码行数:104,代码来源:verifier.py

示例15: load

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import get_node [as 别名]
class RST_DT:
    def load(self, path2file):
        self.id_EDUs = []
        self.EDU = {}
        self.treeNS = Tree()
        self.tree = Tree()
        # nombre max d'espace pour init id_parents
        with open(path2file, "r") as f:
            max_space = 0
            nb_line = 0
            for i, line in enumerate(f):
                nb_space = 0
                for c in line:
                    if c == " ":
                        nb_space += 1
                    else:
                        break
                if nb_space > max_space:
                    max_space = nb_space
                nb_line += 1
        with open(path2file, "r") as f:
            id_parents = [0] * max_space
            NS_parents = [0] * max_space
            for i, line in enumerate(f):
                # nombre d'espace détermine le parent
                nb_space = 0
                for c in line:
                    if c == " ":
                        nb_space += 1
                    else:
                        break
                space = nb_space / 2
                id_parents[space] = i
                parent = id_parents[space - 1]
                reg = "\(([\w\-\[\]]+)|(_!.+!_)"  # récupération du contenu
                match = re.findall(reg, line)[0]
                if match[0] == "":
                    content = match[1]  # feuille EDU
                    self.id_EDUs.append(i)
                    # print content
                    self.EDU[i] = re.findall("_!(.*)!_", content)
                else:
                    content = match[0]
                    reg2 = "\[(N|S)\]"  # récupération NS
                    match2 = re.findall(reg2, content)
                    NS_parents[space] = match2  # ['N','S']
                # création du noeud
                if i == 0:
                    self.tree.create_node(content, 0)
                    self.treeNS.create_node("Root", 0)
                else:
                    id_NS = len(self.tree.is_branch(parent))  # 0 ou 1 car arbre binaire
                    self.tree.create_node(content, i, parent=parent)
                    self.treeNS.create_node(NS_parents[space - 1][id_NS], i, parent=parent)

    def toDEP(self):

        ###############################
        # Etape 1 : construction du head_tree

        # parcours en largeur de tree afin de récupérer chaque id_node
        # pour chaque profondeur (init à 0) _! sans compter !_ les feuilles (EDUs)

        nodes_depth = [-1] * self.tree.size()
        for i in xrange(self.tree.size()):
            id_nodes = [0]
            depth = [999] * self.tree.size()
            while id_nodes:  # False if empty
                id_node = id_nodes.pop(0)
                node = self.tree.get_node(id_node)
                if node.bpointer != None:
                    node_parent = self.tree.get_node(node.bpointer)
                    depth[node.identifier] = depth[node_parent.identifier] + 1
                else:
                    depth[node.identifier] = 0
                if id_node == i:
                    # print 'noeud ',i,' en profondeur', depth[node.identifier]
                    if node.fpointer:
                        nodes_depth[i] = depth[i]
                    break
                if node.fpointer:
                    id_nodes.append(node.fpointer[0])
                    id_nodes.append(node.fpointer[1])
        # print nodes_depth

        id_nodes_depth = []
        for d in xrange(self.tree.depth()):
            id_nodes_depth.append([])
            for i in xrange(self.tree.size()):
                if nodes_depth[i] == d:
                    id_nodes_depth[d].append(i)
        # print id_nodes_depth

        #
        # construction du head_tree

        head_tree = [-1] * self.treeNS.size()
        # pour chaque noeud (non EDU/feuille) en partant de la plus grande profondeur dans l'arbre
        for d in range(len(id_nodes_depth) - 1, -1, -1):
            for id_node in id_nodes_depth[d]:
#.........这里部分代码省略.........
开发者ID:niki-rohani,项目名称:Automatic_summarization_using_RST_DT,代码行数:103,代码来源:rst2dep.py


注:本文中的treelib.Tree.get_node方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。