为了账号安全,请及时绑定邮箱和手机立即绑定

在小网络x图中复制未通过边连接的节点

在小网络x图中复制未通过边连接的节点

catspeake 2021-12-16 15:56:42
我正在尝试使用 networkx 创建一个图书图网络。在我的示例案例中,我从书架上拿走了两本书,并使用 api 从 Goodreads 中提取了“类似书籍”。使用以下代码将类似的书籍读入字典 d1。d1 看起来像这样: #use requests to get book details based on id id_lst=[3431,6900] print(id_lst) from goodreads import client gc = client.GoodreadsClient(api_key,api_secret) d1 = {} for id in id_lst[:2]:     book = gc.book(id)     similar = book.similar_books     similar_small = similar[0:4]     print(book)test=similar[1]#print(test)d1.update({book:similar_small})print(d1){The Five People You Meet in Heaven: [Harry Potter and the Deathly Hallows (Harry Potter, #7), Lord of the Flies, A Wrinkle in Time (Time Quintet, #1), Speak], Tuesdays with Morrie: [Harry Potter and the Deathly Hallows (Harry Potter, #7), Lord of the Flies, Speak, Anna Karenina]}  然后我使用下面的代码将这本字典变成一个边缘列表:    output = []    for key in d1:        for i in d1[key]:        output.append((key, i))    print(output)这将返回此边缘列表。[(The Five People You Meet in Heaven, Harry Potter and the Deathly Hallows (Harry Potter, #7)), (The Five People You Meet in Heaven, Lord of the Flies), (The Five People You Meet in Heaven, A Wrinkle in Time (Time Quintet, #1)), (The Five People You Meet in Heaven, Speak), (Tuesdays with Morrie, Harry Potter and the Deathly Hallows (Harry Potter, #7)),(Tuesdays with Morrie, Lord of the Flies), (Tuesdays with Morrie, Speak), (Tuesdays with Morrie, Anna Karenina)]然后我尝试将其读入 networkx 以构建图形。    G = nx.from_edgelist(output)尽管例如“哈利波特与死亡圣器(哈利波特,#7)”出现两次,但它会返回一个包含两个不相连的不同簇的图,因此它应该与“你在天堂遇到的五个人”相关联'和'与莫里的星期二'。总的来说,我对 Python 和图网络都很陌生,我正在尝试自己构建一个小项目,因为我的组织开始研究它们,我想建立自己的理解。
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

我没有 goodreads api 密钥,所以我构建了下面的示例,使用字母来表示与上面的书籍数据相同的结构。


赶紧跑:


import networkx as nx


d1 = {('a','c'),('a','d'),('a','e'),('a','f'),('b','c'),('b','d'),('b','f'),('b','g')}


G = nx.from_edgelist(G)


nx.draw(G)

如果一切正常,你应该看到

//img1.sycdn.imooc.com//61baf16600011def04820316.jpg

这意味着 networkx 工作正常,问题在于您传递的数据


查看完整回答
反对 回复 2021-12-16
?
炎炎设计

TA贡献1808条经验 获得超4个赞

在我们的谈话之后,我建议问题在于您的书名没有正确转义。这是我们做的唯一不同的事情(因为你用 API 选择它,我们复制粘贴它并手动转义)。


查看完整回答
反对 回复 2021-12-16
  • 2 回答
  • 0 关注
  • 193 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号