加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
dependency_graph.py 1.73 KB
一键复制 编辑 原始数据 按行查看 历史
Xiao Luwei 提交于 2020-03-08 11:23 . Add files via upload
# -*- coding: utf-8 -*-
import numpy as np
import spacy
import pickle
nlp = spacy.load('en_core_web_sm')
# https://spacy.io/docs/usage/processing-text
def dependency_adj_matrix(text):
document = nlp(text)
seq_len = len(text.split())
matrix = np.zeros((seq_len, seq_len)).astype('float32')
# https://spacy.io/docs/api/token
for token in document:
if token.i < seq_len:
matrix[token.i][token.i] = 1
for child in token.children:
if child.i < seq_len:
matrix[token.i][child.i] = 1
matrix[child.i][token.i] = 1
return matrix
def process(filename):
fin = open(filename, 'r', encoding='utf-8', newline='\n', errors='ignore')
lines = fin.readlines()
fin.close()
idx2graph = {}
fout = open(filename+'.graph', 'wb')
for i in range(0, len(lines), 3):
text_left, _, text_right = [s.lower().strip() for s in lines[i].partition("$T$")]
aspect = lines[i + 1].lower().strip()
adj_matrix = dependency_adj_matrix(text_left+' '+aspect+' '+text_right)
idx2graph[i] = adj_matrix
pickle.dump(idx2graph, fout)
fout.close()
if __name__ == '__main__':
process('./datasets/acl-14-short-data/train.raw')
process('./datasets/acl-14-short-data/test.raw')
process('./datasets/semeval14/restaurant_train.raw')
process('./datasets/semeval14/restaurant_test.raw')
process('./datasets/semeval14/laptop_train.raw')
process('./datasets/semeval14/laptop_test.raw')
process('./datasets/semeval15/restaurant_train.raw')
process('./datasets/semeval15/restaurant_test.raw')
process('./datasets/semeval16/restaurant_train.raw')
process('./datasets/semeval16/restaurant_test.raw')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化