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


Python Tree.create_node方法代码示例

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


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

示例1: test_paste_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
 def test_paste_tree(self):
     new_tree = Tree()
     new_tree.create_node("Jill", "jill")
     new_tree.create_node("Mark", "mark", parent="jill")
     self.tree.paste("jane", new_tree)
     self.assertEqual("jill" in self.tree.is_branch("jane"), True)
     self.tree.remove_node("jill")
开发者ID:Mondego,项目名称:pyreco,代码行数:9,代码来源:allPythonContent.py

示例2: test_02_get_hierarchy_for_module_returns_single_node_when_nothing_depend_on_module

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
	def test_02_get_hierarchy_for_module_returns_single_node_when_nothing_depend_on_module(self, mock_client):
		"""
		Test that get_hierarchy_for_module returns a single node tree structure if no dependent modules are found
		:param mock_client: A mocked out version of erppeek.Client
		:return:
		"""
		# Mock Up
		mock_dp = DependencyGraph
		orig_mod_search = mock_dp.module_search
		orig_dep_search = mock_dp.dependency_search
		orig_client_search = mock_client.search
		mock_dp.module_search = MagicMock(return_value=[666])
		mock_dp.dependency_search = MagicMock(return_value=[])

		mock_dg = mock_dp('valid_module')
		test_hierarchy = Tree()
		test_hierarchy.create_node('valid_module', 'valid_module')
		self.assertEqual(mock_dg.hierarchy.to_json(), test_hierarchy.to_json(), 'get_hierarchy_for_module did not return [] when finding no dependent modules')

		# Mock Down
		mock_client.stop()
		mock_dp.module_search.stop()
		mock_client.search.stop()
		mock_client.search = orig_client_search
		mock_dp.dependency_search.stop()
		mock_dp.module_search = orig_mod_search
		mock_dp.dependency_search = orig_dep_search
开发者ID:Gimpneek,项目名称:odoo_dependency_graph,代码行数:29,代码来源:test_module_discovery.py

示例3: __init__

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
class Conversation:
    def __init__(self, tweet):
        self.root_tweet = tweet
        self.conversation_tree = Tree()
        self.conversation_tree.create_node(tweet, tweet)
        self.depth = int()
        self.tweets_id = list()
        self.tweets_id.append(tweet)
        self.width = int()

    def add_replay(self, tweet, parent_tweet):
        self.conversation_tree.create_node(tweet, tweet, parent=parent_tweet)
        self.tweets_id.append(tweet)

    def set_depth(self):
        self.depth = self.conversation_tree.depth() + 1

    def find_depth(self):
        return self.depth

    def get_tweets_id(self):
        return self.tweets_id

    def set_width(self):
        self.width = len(self.tweets_id)

    def find_width(self):
        return self.width

    def get_conversation_tree(self):
        return self.conversation_tree
开发者ID:anukat2015,项目名称:Twitter_DA_Recognition,代码行数:33,代码来源:conversation.py

示例4: main

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

示例5: TreePipeline

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

示例6: Scansion

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
class Scansion(object):
    """
        .src    : list of strings
    """

    #///////////////////////////////////////////////////////////////////////////
    def __init__(self, source_file):
        """
                Scansion.__init__

                source_file     : (src) source file's name.
        """
        self.htree = Tree()
        self.src = []

        # creating root node (level 0) :
        self.htree.create_node(tag           = "root",
                               identifier    = "root",
                               data          = Hypothesis(htree = self.htree,
                                                          level=0,
                                                          language=None,
                                                          src=source_file))

        # calling root node :
        msg(0, "Calling the root node.")
        stop = False
        while not stop:
            leaves_to_be_extended = [leave for leave in self.htree.leaves() if not leave.data.dead]

            for leave in leaves_to_be_extended:
                leave.data.go_on()

            if len(leaves_to_be_extended)==0:
                stop = True
开发者ID:suizokukan,项目名称:anceps,代码行数:36,代码来源:pyscansion.py

示例7: visit_root

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
 def visit_root(self, node, tree=None):
     tree = Tree()
     root = repr(node)
     tree.create_node(root, root)
     for child in node.children:
         tree = self.visit(child, tree=tree)
     return tree
开发者ID:t2y,项目名称:python-study,代码行数:9,代码来源:visitor_treelib.py

示例8: parse_xml

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
def parse_xml(path):
    tree = ET.parse(path)
    bill_list = []
    destination = "console"

    # eg:       (cox, "[email protected]")                  (rent, 2000)
    #          /                                 \            &    /            \
    #      (Evan, 0.5)                        (Jason, 0.5)       (Evan, 0.45)   (Jason, 0.55)
    for bill in tree.findall("bill"):
        billname = bill.get("name")
        bill_tree = Tree()
        bill_value = bill.get("fixed")
        if bill_value is None:
            bill_value = bill.get("from_email")
        bill_tree.create_node(tag=billname, identifier=billname, data=bill_value)

        for user in bill.findall("user"):
            username = user.get("name")
            ratio = user.get("ratio")
            bill_tree.create_node(tag=username, identifier=username, parent=billname, data=ratio)
        bill_list.append(bill_tree)

    # Get the location to dump our results
    for d in tree.findall("output"):
        destination = d.get("destination")

    return (bill_list, destination)
开发者ID:jramapuram,项目名称:rentbot,代码行数:29,代码来源:Rentbot.py

示例9: test_show_data_property

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

示例10: _get_random_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
 def _get_random_tree(self, start, max_depth=999):
     """
     Returns a random tree from PCFG starting with symbol 'start'
     depth: the maximum depth of tree
     """
     t = Tree()
     t.create_node(ParseNode(start,''))
     
     # get ids of not expanded nonterminals in tree
     nodes_to_expand, depth = self.__get_nodes_to_expand_and_depth(t)
     
     while len(nodes_to_expand) > 0:
         # for each non terminal, choose a random rule and apply it
         for node in nodes_to_expand:
             symbol = t[node].tag.symbol
             
             # if tree exceeded the allowed depth, expand nonterminals
             # using rules from terminating_rule_ids
             if depth >= (max_depth-1):
                 # choose from rules for nonterminal from terminating_rule_ids
                 rhsix = np.random.choice(self.grammar.terminating_rule_ids[symbol], size=1)
             else:
                 # choose from rules for nonterminal according to production probabilities
                 rhsix = np.random.choice(len(self.grammar.rules[symbol]), p=self.grammar.prod_probabilities[symbol], size=1)
             
             t[node].tag.rule = rhsix[0] # index of production rule used when expanding this node
             rhs = self.grammar.rules[symbol][rhsix[0]]
             for s in rhs:
                 t.create_node(tag=ParseNode(s,''), parent=node)
         
         nodes_to_expand, depth = self.__get_nodes_to_expand_and_depth(t)
     
     return t
开发者ID:gokererdogan,项目名称:ShapeGrammar,代码行数:35,代码来源:pcfg_tree.py

示例11: build_directory_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
def build_directory_tree(service):
    print colored("*** Building directory tree ***", 'blue')
    
    # initialize a new directory structure
    directory = Tree()
    directory.create_node("Root", "root")
    page_token = None
    while True:
        try:
            param = {}
            if page_token:
                param['pageToken'] = page_token
            
            # Get children of folderID
            children = service.children().list(folderId='root', **param).execute()

            # For each child in folder, get ID, name and Type
            # and write to the directory tree
            for child in children.get('items', []):
                try:
                    file__ = service.files().get(fileId=child['id']).execute()
                    directory.create_node(file__['title'], child['id'], parent = 'root', data=node('root', child['id'], file__['title'], file__['mimeType']))
                except errors.HttpError, error:
                    print 'An error occurred: %s' % error
            
            # Get next page token for current folderID
            page_token = children.get('nextPageToken')
            if not page_token:
                break
        except errors.HttpError, error:
            print colored('An error occurred: %s', 'red') % error
            break
开发者ID:rohitdureja,项目名称:Terminal-Drive,代码行数:34,代码来源:directorytree.py

示例12: test_modify_node_identifier_root

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
 def test_modify_node_identifier_root(self):
     tree = Tree()
     tree.create_node("Harry", "harry")
     tree.create_node("Jane", "jane", parent="harry")
     tree.update_node(tree['harry'].identifier, identifier='xyz', tag='XYZ')
     self.assertTrue(tree.root == 'xyz')
     self.assertTrue(tree['xyz'].tag == 'XYZ')
     self.assertEqual(tree.parent('jane').identifier, 'xyz')
开发者ID:caesar0301,项目名称:treelib,代码行数:10,代码来源:test_tree.py

示例13: merge_trees

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
def merge_trees(t1, t2, tick):
  t = Tree()
  identifier = -tick # using negative numbers as identifiers, positive numbers are ids for the leaf nodes
  name = "new_cluster_%s" % tick
  t.create_node(name, identifier)
  t.paste(identifier, t1)
  t.paste(identifier, t2)
  return t, name
开发者ID:sacry-,项目名称:AdaptiveAgents,代码行数:10,代码来源:trees.py

示例14: create_tree

# 需要导入模块: from treelib import Tree [as 别名]
# 或者: from treelib.Tree import create_node [as 别名]
def create_tree(indexed_titles, root, children=None):
  t = Tree()
  identifier = indexed_titles[root]
  t.create_node(root, identifier)
  if children:
    for sub_tree in children:
      t.paste(identifier, sub_tree)
  return t
开发者ID:sacry-,项目名称:AdaptiveAgents,代码行数:10,代码来源:trees.py

示例15: AcquisitionChain

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


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