如何将属性添加到节点?

2024-04-26 09:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试向我正在创建的节点添加类似名称的属性,但收到错误消息。 error

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

这就是我得到的错误。 error message

      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 interactions
for 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)

Tags: thetonameinaddidnodeis
3条回答

这是因为add_node是一个函数。你不能给函数赋值

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

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

UPD:由于您使用的是networkx库,因此您可以查看他们关于添加节点函数here的文档

我相信你想做的是:

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

或者像提比一样。M指出,你也可以做:

G.add_node(tweeter_id, name=tweeter_name)

而不是你的

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分配了一些字符串)

正如你从the documentation读到的

Use keywords set/change node attributes:

>>> G.add_node(1,size=10)

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

因此,使用关键字参数name来定义属性。
(注意:不带引号,否则它将是一个str,并将导致您面对的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)

它应该会起作用

相关问题 更多 >