依存树

import spacy
import networkx as nx
import re
import nltk
import nltk.data
#情感分析
from textblob import TextBlob
from nltk.corpus import sentiwordnet
from collections import defaultdict

nlp=spacy.load('en_core_web_sm')

alltext=[]
sentext=[]
juzi=''
file = open("C:/Users/24224/Desktop/Harry Potter 1 .txt","r",encoding='utf-8')
content = file.read()
s2 = ''.join(i for i in content)
#print(s2)
blob = TextBlob(s2)
#分句
blob = blob.sentences
print(blob[1])

for i in range(len(blob)):
    print("内容是:",blob[i],blob[i].sentiment)
#dep_ 为nsubj
def splitSentence(paragraph):
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    sentences = tokenizer.tokenize(paragraph)
    return sentences

with open("C:/Users/24224/Desktop/课程内容集合/自然语言处理/Harry Potter 1 - Sorcerer's Stone.txt","rb")as text:
    for lines in text:
        lines=str(lines)
        if lines=='\n':
            continue
        else:
            line =lines.strip().split('\n')
            #juzi+=str(line)
            alltext.append(line)
    #alltext=splitSentence(juzi)
    #print(alltext)
        #alltext.append(line)

    for sens in alltext:
        text_sentence=nlp(sens[0])
        for sentence in text_sentence.sents:
            sentext.append(sentence)
    print("sentext",sentext)
    word_pos_dict=defaultdict(str)
    for sen in sentext:
        H=re.findall(r'\bHarry\b|\bPotter\b',str(sen))
        if H:
            doc=nlp(str(sen))
        else:
            continue
        for token in doc:
            word_pos_dict[token.dep_]=token.text
        if word_pos_dict['nsubj']!='' and word_pos_dict['ROOT']!="" and word_pos_dict['dobj']!="":
            if word_pos_dict['nsubj']=='Harry' or word_pos_dict['dobj']=="Harry":
                print(word_pos_dict['nsubj'],word_pos_dict['ROOT'],word_pos_dict['dobj'])
        word_pos_dict=defaultdict(str)

#pobj介词宾语, dobj 直接宾语,det限定词,nsubj名词主语,nn 名词复合修饰语
doc=nlp("I come to bring Harry to his aunt and uncle.")
#for token in doc:
    #print(("token.head.text,token.text,token.dep_",token.head.text,token.text,token.dep_))
#spacy.display.serve(doc,style='dep')
edge=[]
for token in doc:
    for child in token.children:
        edge.append(('{0}'.format(token.lower_),'{0}'.format(child.lower_)))
graph=nx.Graph(edge)
#pobj介词宾语, dobj 直接宾语,det限定词,nsubj名词主语,nn 名词复合修饰语
print(graph)

entity1='I'.lower()
entity2='Harry'.lower()
print(nx.shortest_path_length(graph,source=entity1,target=entity2))
print(nx.shortest_path(graph,source=entity1,target=entity2))

nlp=spacy.load('en_core_web_sm')
doc=nlp( "spaCy uses the terms head and child to describe the words" )
for token in doc:
    print('{0}({1}) <-- {2} -- {3}({4})'.format(token.text, token.tag_, token.dep_, token.head.text, token.head.tag_))

from spacy import displacy
nlp = spacy.load('en_core_web_sm')
doc = nlp( "spaCy uses the terms head and child to describe the words" )
displacy.serve(doc, style='dep')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是一个可以提取句子的python程序: ``` import spacy nlp = spacy.load("zh_core_web_sm") def extract_sentence_from_dependency_tree(text): doc = nlp(text) sentences = [sent.text for sent in doc.sents] return sentences text = "这是一个句子。这是另一个句子。" sentences = extract_sentence_from_dependency_tree(text) for sent in sentences: print(sent) ``` 这个程序使用了spacy的中文模型,并调用了它的`sents`属性来提取句子。 输出结果: ``` 这是一个句子。 这是另一个句子。 ``` ### 回答2: 编写一个Python程序以从语义依存(Semantic Dependency Tree)中提取句子,可以按照以下步骤进行: 步骤1:安装依赖库 确保计算机上已安装所需的库,如`nltk`和`stanfordnlp`。 步骤2:导入所需库 在Python脚本中导入必要的库,如: ```python import nltk import stanfordnlp ``` 步骤3:初始化StanfordNLP 使用StanfordNLP库中的`stanfordnlp.Pipeline`来初始化自然语言处理管道,以便进行语义依存分析。例如: ```python nlp = stanfordnlp.Pipeline(lang='zh') ``` 步骤4:定义句子提取函数 编写一个函数,该函数接受一个文本输入,并返回提取的句子列表。函数内的代码可以按照以下方式完成: ```python def extract_sentences(text): # 使用StanfordNLP库进行语义依存分析 doc = nlp(text) sentences = [] # 对每个句子进行处理 for sent in doc.sentences: sentence = [] # 提取依存关系中的每个词语 for word in sent.words: sentence.append(word.text) # 将句子添加到句子列表中 sentences.append(' '.join(sentence)) return sentences ``` 步骤5:调用函数进行句子提取 在需要提取句子的地方,调用上述定义的函数,并将文本作为参数传递。例如: ```python text = "这是一段示例文本。这个Python程序将从语义依存中提取句子。" sentences = extract_sentences(text) print(sentences) ``` 运行该程序,将输出提取的句子列表: ``` ['这是 一段 示例 文本 。', '这个 Python 程序 将 从 语义 依存 中 提取 句子 。'] ``` 这样,你就能够通过这个程序从语义依存中提取句子了。请注意,这只是一个基本的示例,你可以根据具体需求进行修改和扩展。 ### 回答3: 编写一个Python程序,从语义依存中提取句子需要考虑以下步骤: 1. 导入所需的Python库,如NLTK和Stanford CoreNLP。 2. 初始化Stanford CoreNLP,创建一个依存关系解析器来对文本进行语义依存分析。 3. 输入待分析的文本。 4. 使用Stanford CoreNLP的依存关系解析器,将输入的文本转换为语义依存。 5. 从语义依存中提取句子。这可以通过遍历依存的节点来实现。每个节点代表一个词语,在节点中,可以找到该词语的依存关系和依存关系的父节点。 6. 在遍历过程中,将属于同一个句子的词语组合起来。一个句子通常以根节点为起点,通过依存关系连接多个词语。 7. 返回提取到的句子作为程序的输出。 以下是一种可能的实现方案的伪代码示例: ```python import nltk from nltk.parse.corenlp import CoreNLPServer # 启动Stanford CoreNLP服务器 server = CoreNLPServer("path/to/stanford-corenlp", port=9000) server.start() # 初始化依存关系解析器 dep_parser = nltk.parse.corenlp.CoreNLPServer(url="http://localhost:9000") # 输入待分析的文本 text = "我喜欢学习自然语言处理。" # 使用依存关系解析器分析文本并得到依存 parsed_text = dep_parser.parse_text(text) # 提取句子 sentences = [] for sent in parsed_text.sentences: words = [word['word'] for word in sent['words']] sentences.append(''.join(words)) # 关闭Stanford CoreNLP服务器 server.stop() # 打印句子 for sentence in sentences: print(sentence) ``` 这段代码通过与Stanford CoreNLP服务器的通信,实现了从语义依存中提取句子的功能。请注意,为了运行此程序,需要先在本地安装Stanford CoreNLP,并对代码中相关的路径进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值