自动文本摘要 Text Summarization

文本摘要就是对原始文档的要点进行总结。比如新闻关键词的提炼,百度搜索引擎等。

自动文本摘要一般有两种方法: 提取式与抽象式。

从网页中抽取数据步骤:

1:导入相关库/包

    Beautiful Soup(bs)是一个能从HTML和XML文件中抽出数据的Python库。 Urllib是一个程序包,里面含有处理URL的多个模块。
    re 这个模块提供了各种正则表达式匹配操作。 nltk是一个基于Python的类库,是一个领先的自然语言处理的编程与开发平台。它为50多个语料和词库资源提供了易用的交互接口,比如WordNet。它同时也提供了一整套来对文本进行分类、分词、词干提取、标签化、解析、语义推理的文本处理库。 heapq 这个模块提供了堆队列算法(优先队列算法)的一种实现。

2:抽取数据

3:数据清洗

4:建立直方图

5: 计算句子分值

6:找出最适合的句

import bs4 as bs
import urllib.request
import re
import nltk
import heapq
nltk.download(stopwords)
nltk.download(punkt)
#将网页内容抽取下来,选取的是Artificial Neural Network (人工神经网络)这个维基页
page = urllib.request.urlopen("https://en.wikipedia.org/wiki/Artificial_neural_network").read()
soup = bs.BeautifulSoup(page,lxml)
#print(page)     #print the page
#2.抽取数据
#用BeautifulSoup库来解析文档并且用一种漂亮的方式来抽取文本
#print(soup.prettify)
text = ""
for paragraph in soup.find_all(p):
   text += paragraph.text
#print(text)

#3.数据清洗

#去除文本中类似于[1],[2] 样子的上标索引
text = re.sub(r[[0-9]*], ,text)
#去除了所有额外的空格,只留下必要的一个空格。
text = re.sub(rs+, ,text)
#转换成小写字母
clean_text = text.lower()
#去除了所有额外的标点符号、数字、额外的空格
clean_text = re.sub(rW, ,clean_text)
clean_text = re.sub(rd, ,clean_text)
clean_text = re.sub(rs+, ,clean_text)
#利用sent_tokenize()将大段文本分割成了一个个句子
sentences = nltk.sent_tokenize(text)
stop_words = nltk.corpus.stopwords.words(english)
print(sentences)
#print(stop_words)  #list

#4:建立直方图
#创建一个空的字典word2count
word2count = {}  #line 1
#利用for循环并利用word_tokenize方法将clean _text分割成多个词并放入word变量中
for word in nltk.word_tokenize(clean_text):     #line 2
    #检查某个词word是否“没有出现在”停用词stop_words列表中。然后再判断该词是否“没有在”字典的键值中1,否则就在字典中将该词的计数加1
   if word not in stop_words:                  #line 3
       if word not in word2count.keys():
           word2count[word]=1
       else:
           word2count[word]+=1
            #计算每个直方的权重(请看输出,你就可以看到这些权重并不是简单计数,比如‘artificial’:0.3620689)
for key in word2count.keys():                   #line 4
   word2count[key]=word2count[key]/max(word2count.values())

#5: 计算句子分值
# Calculate the score

#创建一个空的字典sent2score
sent2score = {}
#利用for循环将一个个句子从sentence列表中放入sentence变量汇总(在步骤3,我们创建了sentences列表)
for sentence in sentences:
#转换为小写字母并将句子分割成词,放入word变量中
    for word in nltk.word_tokenize(sentence.lower()):
#利用if条件判断word是否在字典word2count的键值中word2count.keys()
        if word in word2count.keys():
#将长度设定为小于30
            if len(sentence.split( )) < 30:
#sentence句子“不在”字典sent2score的键值中,就将该句子作为键key放入字典sent2score并将值value置为word2count字典中该词的计数。否则就将该句对应的键值(即句子的分值)加1
                if sentence not in sent2score.keys():
                    sent2score[sentence] = word2count[word]
                else:
                    sent2score[sentence] += word2count[word]
            #        print(sent2score[sentence])

#6:找出最适合的句子
#利用heapq包来找出了7个最适合的句子来作为维基的这篇ANN文章的摘要
best_sentences = heapq.nlargest(7,sent2score,key=sent2score.get)

for sentences in best_sentences:

   print(sentences,
)
经验分享 程序员 微信小程序 职场和发展