簡體   English   中英

在小型networkx圖中復制未通過邊緣連接的節點

[英]Duplicates nodes not connected by edge in small networkx graph

我正在嘗試使用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詞典的代碼編輯2:這是我繪制圖形時得到的結果

在此處輸入圖片說明

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密鑰,因此我在下面的示例中使用字母表示與您的圖書數據相同的結構。

趕緊跑:

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工作正常,問題出在您傳遞的數據上

交談之后,我認為問題出在您的書名中,無法正確解決。 這是我們唯一不同的方式(因為您使用API​​進行選擇,然后我們將其復制粘貼並手動轉義)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM