UCINET网络图形绘制的Python代码

2024-04-19 14:55:02 发布

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

我用beauthoulsoup收集了一些数据,并保存为.txt文件。数据来自电影评论IMDB.com网站 我发现了一个很好的单词计数python代码,所以我可以制作一个单词频率excel表格。然而,我不能仅仅用频率表来绘制图形。在

我想用UCINET绘制语义网络图(节点大小应基于中间性中心度)。

我的问题是如何将文本文件转换成邻接矩阵数据来绘制UCINET图形。 像这样http://www.umasocialmedia.com/socialnetworks/wp-content/uploads/2012/09/senatorsxsenators1.png 我想用评论家用的词画网络图。在

(如果两个单词出现在同一个句子中,当它们行和列行匹配时,计算出现的频率)

或者。你能告诉我如何用Python代码绘制网络图吗??


Tags: 文件数据代码txtcom图形电影评论
1条回答
网友
1楼 · 发布于 2024-04-19 14:55:02

制作一个2D 20x20数组,遍历每个输入字符串,然后使用该字符串更新矩阵:

adjacency_matrix = [[0 for _ in range(20)] for _ in range(20)]


def get_lines(filename):
    """Returns the lines in the file"""
    with open(filename, 'r') as fp:
        return fp.readlines()


def update_matrix(matrix, mapping, string):
    """Update the given adjacency matrix using the given string."""                                        
    words = [_ for _ in re.split("\s+", string) if _ in mapping.keys()]            
    for word_1 in words:                                                           
        for word_2 in words:                                                       
            matrix[mapping[word_1]][mapping[word_2]] += 1


if __name__ == "__main__":
    words_in_matrix = ["X-men", "awesome", "good", "bad", ... 16 more ...]
    mapping = {word: index for index, word in enumerate(words_in_matrix)}

    for line in get_lines("ibdb.txt"):
        update_matrix(adjacency_matrix, mapping, line)
    print(adjacency_matrix)

一个类似于update_matrix的函数可能很有用,其中matrix是邻接矩阵,mapping是单词到邻接矩阵中索引的映射,string是示例回顾。在

你需要根据你的需要修改这个。输入可能有句点或其他噪声字符,这些字符需要去除。在

相关问题 更多 >