【发布时间】:2019-03-27 06:09:39
【问题描述】:
我正在尝试使用 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})
感谢所有帮助过的人!
【问题讨论】:
-
您能否轻松地包含用于构建
d1对象的代码?它看起来与文档示例不同:edgelist= [(0,1)] -
你如何检查你的图有两个集群?我将您的代码复制到 Jupyter Notebook,它向我展示了一个大集群。
-
请向我们展示
nx.draw(G)的结果。看起来您使用了某种 matplotlib 示例,该示例对无向图效果不佳。 -
嗯,很奇怪。我使用确切的代码并拥有一个集群。请尝试
G = nx.from_dict_of_lists(d1),如果没有帮助,请编写您的networkx版本:nx.__version__ -
感谢您对这些人的帮助。已经尝试使用 dict_of_lists,我仍然得到相同的结果。