为了账号安全,请及时绑定邮箱和手机立即绑定

如何给节点添加属性?

如何给节点添加属性?

郎朗坤 2023-10-06 16:39:19
我一直在尝试向我正在创建的此节点添加名称等属性,但收到错误消息。 错误  # add name as a property to each node    # with networkX each node is a dictionary    G.add_node(tweeter_id,'name' = tweeter_name)    G.add_node(interact_id,'name' = interact_name)这是我得到的错误。 错误信息     File "<ipython-input-31-55b9aecd990d>", line 28        G.add_node(tweeter_id,'name' = tweeter_name)                              ^    SyntaxError: expression cannot contain assignment, perhaps you meant "=="?作为参考,这是整个代码:import networkx as nx# define an empty Directed Graph# A directed graph is a graph where edges have a direction# in our case the edges goes from user that sent the tweet to# the user with whom they interacted (retweeted, mentioned or quoted)#g = nx.Graph()G = nx.DiGraph()# loop over all the tweets and add edges if the tweet include some interactionsfor tweet in tweet_list:    # find all influencers in the tweet    tweeter, interactions = getAllInteractions(tweet)    tweeter_id, tweeter_name = tweeter    tweet_id = getTweetID(tweet)        # add an edge to the Graph for each influencer    for interaction in interactions:        interact_id, interact_name = interaction                # add edges between the two user ids        # this will create new nodes if the nodes are not already in the network        # we also add an attribute the to edge equal to the id of the tweet        G.add_edge(tweeter_id, interact_id, tweet_id=tweet_id)                # add name as a property to each node        # with networkX each node is a dictionary        G.add_node(tweeter_id, tweeter_name)        G.add_node(interact_id, interact_name)
查看完整描述

3 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

正如您可以从文档中读到的

使用关键字设置/更改节点属性:

>>> G.add_node(1,size=10)
>>> G.add_node(3,weight=0.4,UTM=('13S',382871,3972649))

因此,请使用关键字参数name来定义属性。
(注意:没有 Quotes,否则它将是 astr并且会导致SyntaxError您面临的,因为它是对字符串文字的赋值)

做这样的事情:

    # add name as a property to each node
    # with networkX each node is a dictionary
    G.add_node(tweeter_id, name = tweeter_name)
    G.add_node(interact_id, name = interact_name)


查看完整回答
反对 回复 2023-10-06
?
呼唤远方

TA贡献1856条经验 获得超11个赞

发生这种情况是因为add_node是一个函数。而且你不能给函数赋值。

当你尝试时,你正在这样做:

G.add_node(tweeter_id, 'name') = tweeter_name

我相信你想做的是:

G.add_node(tweeter_id, attr_dict={'name': tweeter_name})

或作为提比布人。M指出,你还可以这样做:

G.add_node(tweeter_id, name=tweeter_name)


查看完整回答
反对 回复 2023-10-06
?
繁华开满天机

TA贡献1816条经验 获得超4个赞

而不是你的

G.add_node(tweeter_id,'name') = tweeter_name
G.add_node(interact_id,'name') = interact_name

使用

G.add_node(tweeter_id, tweeter_name)
G.add_node(interact_id, interact_name)

(假设您已将一些字符串分配给变量tweeter_nameinteract_name)。


查看完整回答
反对 回复 2023-10-06
  • 3 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信