使用networkx为每个句子创建图 [英] Creating a graph using networkx for each sentence
本文介绍了使用networkx为每个句子创建图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为句子列表中的每个句子创建一个图形.如果句子包含专有名词,则该词将附加到subject_list.如果单词是普通名词,则将单词附加到object_list上,如果单词是动词,则将单词附加到verb_list上. 如何为每个句子分别创建图?
I want to create a graph for each sentence in the sentence_list. If the sentence contains a proper noun then that word is appended to the subject_list. If the word is a common noun then the word is appended to the object_list and if the word is a verb then it is appended to the verb_list. How can I create a graph separately for each sentence?
sentence_list=['Tom drinks milk', 'Jack plays cricket', 'Tim ate rice']
tag_list=[Tom:'NP',drinks:'VF',milk:'NN',plays:'VF',cricket:'NN',ate:'VF',rice:'NN',Tim:'NP', Jack:'NP']
subject_list=[]
object_list=[]
verb_list=[]
newDict = {}
for sent in sentence_list:
for line in tag_list:
k,v = line.strip().split(':')
newDict[k.strip()] = v.strip()
if v=='NP':
subject_list.append(k)
print('SUBJECT:',subject_list)
if v=='NN':
object_list.append(k)
print('OBJECT',object_list)
if v=='VF':
verb_list.append(k)
print('VERB',verb_list)
import networkx as nx
import matplotlib.pyplot as pl
labels={}
graph = nx.Graph()
for subject in subject_list:
s=subject.decode('utf-8')
graph.add_node(s)
labels[s]=s
for obj in object_list:
b=obj.decode('utf-8')
graph.add_node(b)
labels[b]=b
for verb in verb_list:
v=verb.decode('utf-8')
graph.add_node(v)
labels[v]=v
for s,o,v in subject_list,object_list,verb_list:
graph.add_edge(subject_list[s],object_list[o])
graph.add_edge(object_list[o],verb_list[v])
pos=nx.spring_layout(graph)
nx.draw_networkx(graph, pos=pos, labels=labels)
pl.show()
推荐答案
sentence_list=['Tom drinks milk', 'Jack plays cricket', 'Tim ate rice']
tag_list={'Tom':'NP','Tim':'NP','Jack':'NP','drinks':'VF','milk':'NN','plays':'VF','cricket':'NN','ate':'VF','rice':'NN'}
tag_list_keys = tag_list.keys()
subject_list=[]
object_list=[]
verb_list=[]
def classify(item):
if item in tag_list_keys:
if tag_list[item] == 'NP': subject_list.append(item)
if tag_list[item] == 'NN': object_list.append(item)
if tag_list[item] == 'VF': verb_list.append(item)
def extract(item):
item_split = item.split(' ')
map(classify, item_split)
map(extract, sentence_list)
print('SUBJECT:',subject_list)
print('OBJECT',object_list)
print('VERB',verb_list)
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
for i in range(3):
G.add_node(object_list[i])
G.add_node(verb_list[i])
G.add_node(subject_list[i])
G.add_edge(verb_list[i],object_list[i])
G.add_edge(subject_list[i],verb_list[i])
nx.draw(G, with_labels= True)
plt.show()
希望这对您有用.
这篇关于使用networkx为每个句子创建图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文