python人物关系抽取_Python学习笔记(2) Python提取《釜山行》人物关系

项目原理:

实验基于简单共现关系,编写 Python 代码从纯文本中提取出人物关系网络,并用Gephi

将生成的网络可视化。下面介绍共现网络的基本原理。(共现网络简单的英文介绍)

共现网络的基本原理:

实体间的共现是是一种基于统计信息的提取,关系密切的人物往往会在文中的多段连续出现,通过文中以出现的实体(人名),计算不同实体共同出现的比率和次数,设定一个阈值,大于该阈值认为实体间存在某种联系。

准备:

环境 windows Python3.6

jephi软件

代码:

# -*- coding: utf-8 -*-import

os, sys

importjieba, codecs, math

importjieba.posseg aspseg

names ={} # 姓名字典relationships ={} # 关系字典lineNames =[] # 每段内人物关系# count namesjieba.load_userdict("D:\\ResearchContent\\Exercise_Programm\\PythonExercise\\Python\\dict.txt")

# 加载字典with

codecs.open("D:\\ResearchContent\\Exercise_Programm\\PythonExercise\\Python\\fushan.txt", "r", "utf8") asf

:for

line inf.readlines()

:

poss =pseg.cut(line)

# 分词并返回该词词性

lineNames.append([])

# 为新读入的一段添加人物名称列表for

w inposs

:if

w.flag

!="nr"orlen

(w.word)

<2:continue# 当分词长度小于2或该词词性不为nr时认为该词不为人名

lineNames[

-1

].append(w.word)

# 为当前段的环境增加一个人物if

names.get(w.word)

is None:

names[w.word] =

0

relationships[w.word] ={}

names[w.word]

+=1

# 该人物出现次数加 1

# explore relationshipsfor

line inlineNames:

# 对于每一段for

name1 inline

:for

name2 inline:

# 每段中的任意两个人if

name1 ==name2:

continueif

relationships[name1].get(name2) is None:

# 若两人尚未同时出现则新建项

relationships[name1][name2]=

1else:

relationships[name1][name2] =relationships[name1][name2]

+1

# 两人共同出现次数加 1

# outputwith

codecs.open("busan_node.txt", "w", "gbk") asf

:

f.write("Id Label Weight\r\n")

forname, times innames.items()

:

f.write(name

+" "+

name

+" "+str

(times)

+"

\r\n")

withcodecs.open("busan_edge.txt", "w", "gbk") asf

:

f.write("Source Target Weight\r\n")

forname, edges inrelationships.items()

:for

v, w inedges.items()

:if

w

>3:

f.write(name

+" "+

v

+" "+str

(w)

+"

\r\n")

参考:

修改2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值