我正在尝试使用 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 和图形网络都非常陌生,并且我正在尝试自己构建一个小项目,因为我的组织正在开始研究它们,并且我想建立自己的理解。
编辑:添加了构建 d1 字典的代码 EDIT2:这是我绘制图表时得到的结果
EDIT3:nx.draw(G)的结果
EDIT4:最终编辑 - 全部通过将 api 的输出转换为字符串来解决...
#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)
str_ls=[]
d1 = {}
for id in id_lst[:2]:
book = gc.book(id)
books = str(book)
similar = book.similar_books
similar_small = similar[0:4]
for s in similar_small:
str_b = str(s)
str_ls.append(str_b)
d1.update({books:str_ls})
感谢所有提供帮助的人!
最佳答案
我没有 goodreads api key ,因此我使用字母构建了下面的示例来表示与上面的图书数据相同的结构。
只需运行:
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)
这意味着 networkx 工作正常,问题在于您传递的数据
关于python - 在小型 networkx 图中复制未通过边连接的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55346334/