在小型networkx图中复制未通过边缘连接的节点

时间:2019-03-25 21:00:05

标签: python networkx

我正在尝试使用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)

这将返回一个图形,其中包含两个未连接的不同簇,尽管“哈利·波特与死亡圣器(Harry Potter,#7))”出现了两次,所以应将其连接到“五个人”在天堂见面”和“与莫里星期二见面”。

对于Python和图形网络来说,它们都是非常陌生的东西,并且在我的组织开始研究它们时,我正尝试自己构建一个小项目,我想建立自己的理解。

编辑:添加了构建d1词典的代码 EDIT2:这是我绘制图形时得到的结果

enter image description here

EDIT3:nx.draw(G)的结果

enter image description here

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})

感谢所有提供帮助的人!

2 个答案:

答案 0 :(得分:0)

我没有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)

如果一切正常,您应该会看到enter image description here

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

答案 1 :(得分:0)

在我们交谈之后,我认为问题出在您的书名中,无法正确逃避。这是我们唯一不同的方法(因为您使用API​​进行了选择,然后我们将其复制粘贴并手动转义)。