猿问

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

我正在尝试使用 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 和图网络都很陌生,我正在尝试自己构建一个小项目,因为我的组织开始研究它们,我想建立自己的理解。



catspeake
浏览 194回答 2
2回答

慕尼黑8549860

我没有 goodreads api 密钥,所以我构建了下面的示例,使用字母来表示与上面的书籍数据相同的结构。赶紧跑:import networkx as nxd1 = {('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 工作正常,问题在于您传递的数据

炎炎设计

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

相关分类

Python
我要回答