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


Python Tree.show方法代码示例

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


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

示例1: main

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def main():
  try:
    conf = open(args.config, 'r')
    tempConf = yaml.load_all(conf)

    for line in tempConf:
      list_path = line["ListPath"]
      write_missed = line["WriteMissed"]

    pack_list_file = open(list_path, "r+")
    pack_list = json.load(pack_list_file)

    checked = check(pack_list, write_missed)

    tree = Tree()
    tree.create_node(cur_time, "root")
    generate_tree(checked, tree, "root")

    print "\n"
    tree.show()
    print "\n"

  except KeyboardInterrupt:
    print '\nThe process was interrupted by the user'
    raise SystemExit
开发者ID:FromZeus,项目名称:small_tools_mirantis,代码行数:27,代码来源:check_avail.py

示例2: test_show_data_property

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
 def test_show_data_property(self):
     new_tree = Tree()
     class Flower(object):
         def __init__(self, color):
             self.color = color
     new_tree.create_node("Jill", "jill", data=Flower("white"))
     new_tree.show(data_property="color")
开发者ID:CHEN-JIANGHANG,项目名称:treelib,代码行数:9,代码来源:test_treelib.py

示例3: TreePipeline

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
class TreePipeline(object):

    def open_spider(self, spider):
        self.tree = Tree()
        self.tree.create_node("root", "root")

    def process_item(self, item, spider):
        lst = item['text']
        lst = [x.strip() for x in [y.replace('...', '') for y in lst]]
        item['pagetitle'] = item['pagetitle'].replace('...', '')
        lst[-1] = item['pagetitle']
        for idx, elem in enumerate(lst):
            if idx == 0:
                previous = "root"
            else:
                previous = "|".join(lst[:idx])
            elem = "|".join(lst[:idx + 1])
            # elem = elem.replace('...', '')
            elem = elem.encode('utf-8').decode('utf-8')
            if not self.tree.contains(elem):
                print "Adding node %s" % elem
                self.tree.create_node(elem, elem, parent=previous)
                # self.tree.show()
        return item

    def close_spider(self, spider):
        self.tree.show()
        with open(makepath('data/cats/tree.json'), 'w') as outfile:
            outfile.write(self.tree.to_json())
        self.tree.save2file(makepath('data/cats/tree.tree'))
开发者ID:vlasy,项目名称:skool,代码行数:32,代码来源:pipelines.py

示例4: create_trees

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def create_trees(BP, Roots, NT, n):

    for bp in BP[n-1,0]:
        if bp.name in Roots:
            print '\nTree'
            t = Tree()
            create_tree(t, bp, 0, 1)
            t.show(key=lambda x: x.identifier)
开发者ID:dasolma,项目名称:pyCKY,代码行数:10,代码来源:cky.py

示例5: test_session_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def test_session_tree(beacon, capsys):
  session = beacon.get("test_session2")
  session.sessions_tree.show()
  out1, err1 = capsys.readouterr() 
  t = Tree()
  t.create_node("test_session2", "test_session2")
  t.create_node("test_session", "test_session", parent="test_session2")
  t.show()
  out2, err2 = capsys.readouterr()
  assert out1 == out2
开发者ID:tiagocoutinho,项目名称:bliss,代码行数:12,代码来源:test_session.py

示例6: retrieve_dependencies

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [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

示例7: toy_demo

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def toy_demo():
    
    tree_dict_list = []

    tree_dict_list.append({None : 'A' , 'A' : ['B', 'C'], 'B': 'D', 'C':'E',\
                            'E': ['F','G'],\
                            'D' : '1', 'F' : '2', 'G':'3'})

    tree_dict_list.append({None : 'A' , 'A' : ['B', 'C'], 'B':['D','E'],\
                            'C' : '1', 'D' : '2', 'E':'3'})
    
    tree_dict_list.append({None : 'A' , 'A' : ['B','C', 'D','E'],\
                            'B' : '1', 'C' : '2', 'D' : '3', 'E' : '4'})


    tree_dict_list.append({None : 'A' , 'A' : ['B','C', 'D'], \
                            'B' : ['E', 'F', 'G'], 'C' : ['H', 'I'],\
                            'D' : ['J', 'K', 'L', 'M'], 'E' : ['N', 'O'], \
                            'N' : '1', 'O': '2', 'F': '3', 'G': '4', 'H': '5',\
                            'I': '6', 'J' :'7', 'K': '8', 'L': '9', 'M': '0'})

    tree_dict_list.append({None : 'A' , 'A' : 'B', 'B' : ['C', 'D', 'E'],\
                            'C' : ['H', 'I'], 'D' : ['J', 'K', 'L', 'M'], \
                            'E' : ['N', 'O']})


    for tree_dict in tree_dict_list[0:1]:
        tree = Tree()
        idx = 0
        ids = {None : None}
        for parents ,children in sorted(tree_dict.items()):
            for child in children: 
                ids[child] = idx 
                tree.create_node(child, idx, parent = ids[parents], data = nRange(0,0))
                idx += 1 

        tree.show(idhidden = False)
        genRange(tree, tree.root, 0, 1)
        tree.show(data_property="mRange")

        tree_dep_dict = {ids['1'] : ids['A'], ids['2'] : ids['3'], ids['3'] : ids['1'] }
        hieght_dict =  gen_height_list(tree, tree_dep_dict)
        print hieght_dict

            #hieght_dict = {ids['1']: 3, ids['2'] : 3, ids['3']: 1 }
#        hieght_dict = {ids['1']: 1, ids['2'] : 1, ids['3']: 1, ids['4']: 2 }
#        hieght_dict = { ids['1'] : 1, ids['2'] : 3, ids['3']: 1, ids['4']: 1, \
#                        ids['5'] : 3, ids['6'] : 1, ids['7']: 1, ids['8']: 2, \
#                        ids['9'] : 1, ids['0'] : 1 }
        path_dict    = {}
        gen_suptag(tree, tree.root, hieght_dict, path_dict)
        print sorted([(tree[k].tag, v) for k,v in path_dict.items()])
开发者ID:KatyaPa,项目名称:GFL,代码行数:54,代码来源:get_tags_ex.py

示例8: build_test_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def build_test_tree(sequences):
	
	"""
		Args:
			sequences = a list that contanis the set of sequences. Format [[seq1], [seq2], [...]]
	"""

	tree = Tree() #test tree
	
	#add root to the tree
	node = tree.create_node('empty', 0)

	#get the root id to identify some parents nodes bellow
	root_id = node.identifier

	#just a counter to mantain a id to each node in the tree. 
	i = 0

	#sequence is as list with the inputs off each sequence 
	for sequence in sequences:

		#as tree already have one element, begin the counter at 1.
		i = i + 1

		#get the first element of the sequence
		init = sequence.pop(0)

		#add to the tree
		node = tree.create_node(init, i, parent = root_id)

		#parent to the nexts childs
		parent_id = node.identifier

		#now go through every input in the sequence. Every input will be a node into the teste tree
		for s in sequence:

			#increment the ID counter
			i = i + 1

			#add s node to the tree
			node = tree.create_node(s, i, parent = parent_id)

			#update parent for next iteration
			parent_id = node.identifier

	#to vizualize a representation of the tree in terminal uncomment the line bellow
	if verbose: tree.show()

	return tree
开发者ID:stevao-andrade,项目名称:finite_state_machine,代码行数:51,代码来源:tree.py

示例9: test_show_data_property

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

        sys.stdout = open(os.devnull, "w")  # stops from printing to console

        try:
            new_tree.show()

            class Flower(object):
                def __init__(self, color):
                    self.color = color
            new_tree.create_node("Jill", "jill", data=Flower("white"))
            new_tree.show(data_property="color")
        finally:
            sys.stdout.close()
            sys.stdout = sys.__stdout__  # stops from printing to console
开发者ID:caesar0301,项目名称:treelib,代码行数:18,代码来源:test_tree.py

示例10: FpGrowth

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def FpGrowth(fName):
    
    readFile(fName)
    Cone = getSizeOneItemSet(globOriginalList)
    priorityDict = priorityDic(Cone)
    #print(priorityDict)
    tree = Tree()   
    tree.create_node("{}", "root")
    #reconstruct the whole transction database based on the priority
    counter = 0
    for set in globOriginalList:
        temp = dict()
        for element in set:
            priority = priorityDict.get(element)
            temp.update({element:priority})
            sorted_temp = sorted(temp.items(), key=operator.itemgetter(1))
            sorted_temp.reverse()
        #print(sorted_temp)
        # construct Fp tree
        root = "root"
        for tuple in sorted_temp:
            if(not tree.contains(tuple[0])):
                tree.create_node(tuple[0], tuple[0], root, 0)
                root = tuple[0]
            else: 
                if tuple[0] in tree.is_branch(root):
                    #print("node already in this branch, don't know what to do")
                    #print("going down")
                    root = tuple[0]
                    #print(root)
                else:
                    #print("should create a duplicate node")
                    tree.create_node(tuple[0], counter, root, 0)
                    root = counter
                    counter += 1
                # I need to decide whether to create a new node or not
                # the condition is under this branch if this node exist
                # so I should check the root
    tree.show()
开发者ID:MohanL,项目名称:apriori-Fpgrowth,代码行数:41,代码来源:FpGrowth.py

示例11: tree_test

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def tree_test():
  test_titles = [
    "deletion_mapping", 
    "orthotheca", 
    "genetically_modified_sperm", 
    "category:intelligence"
  ]
  titles = dict((e, idx) for idx, e in enumerate(test_titles))

  # Tree testing
  t = Tree()
  t.create_node("deletion_mapping",15)
  t.create_node("orthotheca",14, parent=15)
  t.create_node("genetically_modified_sperm",13, parent=14)
  t.create_node("category:intelligence",12, parent=14)
  t.show()

  json = t.to_json()
  print "\nAs JSON:"
  print json

  print "\nAnd parsed back into a tree."
  t2 = from_json(json, titles)
  t2.show()
开发者ID:sacry-,项目名称:AdaptiveAgents,代码行数:26,代码来源:trees.py

示例12: compare_actual_folder_with_tree_with_output

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
 def compare_actual_folder_with_tree_with_output(self, root_path: path, expected_music_folder_tree: Tree):
     print("Expecting the following music folder:")
     expected_music_folder_tree.show()
     self.compare_actual_folder_with_tree(root_path, expected_music_folder_tree)
开发者ID:phauer,项目名称:integrate-into-music-folder,代码行数:6,代码来源:integrator_tests.py

示例13: create_dummy_download_folder_with_output

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [as 别名]
def create_dummy_download_folder_with_output(root_path: path, downloads_source_tree: Tree) -> path:
    print("Creating test downloads folder:")
    downloads_source_tree.show()
    created_download_root_folder = create_dummy_download_folder(root_path, downloads_source_tree)
    return created_download_root_folder
开发者ID:phauer,项目名称:integrate-into-music-folder,代码行数:7,代码来源:integrator_tests.py

示例14: WikipediaResolver

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import show [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

示例15: __init__

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

    def __init__(self, lexemas, identifiers, constants):
        self.lexemas = lexemas
        self.identifiers = identifiers
        self.constants = constants
        self.tree = Tree()
        self.branch = []
        self.errors = []

    def pretty_print(self):
        print("\nSyntax analyzer result:")
        self.tree.show(reverse=False)
        for error in self.errors:
            print(error)

    def error(self, text):
        error = Error(text, "Syntax", self.lexeme.row, self.lexeme.column)
        self.tree.create_node(str(error), str(uuid.uuid1()), parent=self.branch[-1])
        self.errors.append(error)
        raise SyntaxAnalizerError

    def expect(self, keyword, scan=False):
        if scan:
            self.lexeme = self.lexemas.pop(0)
        if self.lexeme != keyword:
            self.error("Expected %s" % keyword.upper())

    def __getattribute__(self, name):
        # Decorate every class method
        obj = object.__getattribute__(self, name)
        excluded_methods = ['error', 'analyze', 'expect', 'pretty_print']
        if callable(obj) and obj.__name__ not in excluded_methods:
            return syntax_tree_node(obj, self)
        else:
            return obj

    def analyze(self):
        try:
            self.program()
        except SyntaxAnalizerError:
            pass

    def program(self):
        if self.lexeme == "program":
            self.procedure_identifier()
            self.expect(";")
            self.block()
            self.expect(".", scan=True)
        elif self.lexeme == "procedure":
            self.procedure_identifier()
            self.parameters_list()
            self.expect(";")
            self.block()
            self.expect(";")
        else:
            self.error("Expected PROGRAM or PROCEDURE keyword")

    def block(self):
        self.declarations(scan=False)
        self.expect("begin")
        self.statements_list()
        self.expect("end", scan=True)

    def declarations(self):
        self.constant_declarations(scan=False)
        self.variable_declarations()
        self.math_function_declarations()
        self.procedure_declaration()
        self.lexeme = self.lexemas.pop(0)

    def constant_declarations(self):
        if self.lexeme != "const":
            return "<empty>"
        self.constant_declarations_list()

    def constant_declarations_list(self):
        if self.lexemas[0] == "=":
            self.constant_declaration(scan=False)
        else:
            return "<empty>"
        while self.lexemas[1] == "=":
            self.constant_declarations_list()

    def constant_declaration(self):
        self.constant_identifier(scan=False)
        self.expect("=")
        self.constant()
        self.expect(";")

    def constant(self):
        if self.lexeme == '\'':
            self.complex_constant(scan=False)
        else:
            self.sign(scan=False)
            self.unsigned_constant()

    def variable_declarations(self):
        if self.lexeme == "var":
            self.declarations_list()
#.........这里部分代码省略.........
开发者ID:Alidal,项目名称:signal_compiler,代码行数:103,代码来源:syntaxer.py


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