我正在探索一种数据结构,它可以扩展到子元素并解析为最终元素。但我只想存储前两层。在
例如:让我们假设我从纽约开始,它分为布朗克斯、国王、纽约、皇后区和里士满,但最后他们还是以某种方式决定了美国
我不确定这是否是一个好的例子,但为了让大家明白,这里有更清楚的问题解释。在
A (expands to) B,C,D -> B (expands to) K,L,M -> K resolves to Z
我最初在for循环中编写它,然后使用递归,但是在递归中,我丢失了一些扩展的元素,因此我没有深入到每个展开的元素。我把递归版本和非递归版本都放进去了。我正在寻找一些关于构建这个数据结构的建议,以及什么是最好的方法。在
我为扩展版本中的每个元素调用一个数据库查询,它返回一个项目列表。直到它解析为单一元素。在没有递归的情况下,我不会一直放松钻取,直到其他人决定的最后一个元素。但递归并不相同。我也是python新手,希望在这样的网站上,这不是一个坏问题。在
returnCategoryQuery
是通过调用数据库查询返回项目列表的方法。
def crawlSubCategory(subCategoryList):
level = 1;
expandedList = [];
for eachCategory in subCategoryList:
level = level + 1
print "Level " + str(level) + " " + eachCategory;
#crawlSubCategory(returnCategoryQuery(categoryQuery + eachCategory + "'"));
for subOfEachCategory in returnCategoryQuery(categoryQuery + eachCategory + "'"):
level = level + 1
print "Level " + str(level) + " " + subOfEachCategory;
expandedList.append(crawlSubCategory(returnCategoryQuery(categoryQuery + subOfEachCategory + "'")));
return expandedList;
#Dictionary to save initial category with the rest of cl_to
baseCategoryTree = {};
#categoryResults = [];
# query get all the categories a category is linked to
categoryQuery = "select cl_to from categorylinks cl left join page p on cl.cl_from = p.page_id where p.page_namespace=14 and p.page_title ='";
cursor = db.cursor(cursors.SSDictCursor);
for key, value in idTitleDictionary.iteritems():
for startCategory in value[0]:
#print startCategory + "End of Query";
categoryResults = [];
try:
categoryRow = "";
baseCategoryTree[startCategory] = [];
print categoryQuery + startCategory + "'";
cursor.execute(categoryQuery + startCategory + "'");
done = False;
while not done:
categoryRow = cursor.fetchone();
if not categoryRow:
done = True;
continue;
categoryResults.append(categoryRow['cl_to']);
#crawlSubCategory(categoryResults);
except Exception, e:
traceback.print_exc();
#baseCategoryTree[startCategory].append(categoryResults);
baseCategoryTree[startCategory].append(crawlSubCategory(categoryResults));
你是不是想找“皇后区”并得知它在美国?您是否尝试过用XML编码树,并使用
lxml.etree
查找元素,然后使用getpath
以XPath格式返回路径吗?在这意味着在树中添加第四个顶层,即World,然后您将搜索皇后区并了解到通向皇后区的路径是
World/USA/NewYork/Queens
。你问题的答案永远是XPath
中的第二项。在当然,您总是可以从XML构建一个树,并使用树搜索算法。在
相关问题 更多 >
编程相关推荐