使用NLP建立摘要

做者|Louis Teo
編譯|VK
來源|Towards Data Sciencepython

你有沒有讀過不少的報告,而你只想對每一個報告作一個快速的總結摘要?你是否曾經遇到過這樣的狀況?git

摘要已成爲21世紀解決數據問題的一種很是有幫助的方法。在本篇文章中,我將向你展現如何使用Python中的天然語言處理(NLP)建立我的文本摘要生成器。github

前言:我的文本摘要器不難建立——初學者能夠輕鬆作到!web

什麼是文本摘要

基本上,在保持關鍵信息的同時,生成準確的摘要,而不失去總體意義,這是一項任務。正則表達式

摘要有兩種通常類型:算法

  • 抽象摘要>>從原文中生成新句子。
  • 提取摘要>>識別重要句子,並使用這些句子建立摘要。

應該使用哪一種總結方法

我使用提取摘要,由於我能夠將此方法應用於許多文檔,而沒必要執行大量(使人畏懼)的機器學習模型訓練任務。安全

此外,提取摘要法比抽象摘要具備更好的總結效果,由於抽象摘要必須從原文中生成新的句子,這是一種比數據驅動的方法提取重要句子更困難的方法。app

如何建立本身的文本摘要器

咱們將使用單詞直方圖來對句子的重要性進行排序,而後建立一個總結。這樣作的好處是,你不須要訓練你的模型來將其用於文檔。機器學習

文本摘要工做流

下面是咱們將要遵循的工做流…ide

導入文本>>>>清理文本並拆分紅句子>>刪除停用詞>>構建單詞直方圖>>排名句子>>選擇前N個句子進行提取摘要

(1) 示例文本

我用了一篇新聞文章的文本,標題是蘋果以5000萬美圓收購AI初創公司,以推動其應用程序。你能夠在這裏找到原始的新聞文章:https://analyticsindiamag.com/apple-acquires-ai-startup-for-50-million-to-advance-its-apps/

你還能夠從個人Github下載文本文檔:https://github.com/louisteo9/personal-text-summarizer

(2) 導入庫

# 天然語言工具包(NLTK)
import nltk
nltk.download('stopwords')

# 文本預處理的正則表達式
import re

# 隊列算法求首句
import heapq

# 數值計算的NumPy
import numpy as np

# 用於建立數據幀的pandas
import pandas as pd

# matplotlib繪圖
from matplotlib import pyplot as plt
%matplotlib inline

(3) 導入文本並執行預處理

有不少方法能夠作到。這裏的目標是有一個乾淨的文本,咱們能夠輸入到咱們的模型中。

# 加載文本文件
with open('Apple_Acquires_AI_Startup.txt', 'r') as f:
    file_data = f.read()

這裏,咱們使用正則表達式來進行文本預處理。咱們將

(A)用空格(若是有的話…)替換參考編號,即[1]、[10]、[20],

(B)用單個空格替換一個或多個空格。

text = file_data
# 若是有,請用空格替換
text = re.sub(r'\[[0-9]*\]',' ',text) 

# 用單個空格替換一個或多個空格
text = re.sub(r'\s+',' ',text)

而後,咱們用小寫(不帶特殊字符、數字和額外空格)造成一個乾淨的文本,並將其分割成單個單詞,用於詞組分數計算和構詞直方圖。

造成一個乾淨文本的緣由是,算法不會把「理解」和「理解」做爲兩個不一樣的詞來處理。

# 將全部大寫字符轉換爲小寫字符
clean_text = text.lower()

# 用空格替換[a-zA-Z0-9]之外的字符
clean_text = re.sub(r'\W',' ',clean_text) 

# 用空格替換數字
clean_text = re.sub(r'\d',' ',clean_text) 

# 用單個空格替換一個或多個空格
clean_text = re.sub(r'\s+',' ',clean_text)

(4) 將文本拆分爲句子

咱們使用NLTK sent_tokenize方法將文本拆分爲句子。咱們將評估每一句話的重要性,而後決定是否應該將每一句都包含在總結中。

sentences = nltk.sent_tokenize(text)

(5) 刪除停用詞

停用詞是指不給句子增長太多意義的英語單詞。他們能夠安全地被忽略,而不犧牲句子的意義。咱們已經下載了一個文件,其中包含英文停用詞

這裏,咱們將獲得停用詞的列表,並將它們存儲在stop_word 變量中。

# 獲取停用詞列表
stop_words = nltk.corpus.stopwords.words('english')

(6) 構建直方圖

讓咱們根據每一個單詞在整個文本中出現的次數來評估每一個單詞的重要性。

咱們將經過(1)將單詞拆分爲乾淨的文本,(2)刪除停用詞,而後(3)檢查文本中每一個單詞的頻率。

# 建立空字典以容納單詞計數
word_count = {}

# 循環遍歷標記化的單詞,刪除停用單詞並將單詞計數保存到字典中
for word in nltk.word_tokenize(clean_text):
    # remove stop words
    if word not in stop_words:
        # 將字數保存到詞典
        if word not in word_count.keys():
            word_count[word] = 1
        else:
            word_count[word] += 1

讓咱們繪製單詞直方圖並查看結果。

plt.figure(figsize=(16,10))
plt.xticks(rotation = 90)
plt.bar(word_count.keys(), word_count.values())
plt.show()

讓咱們把它轉換成橫條圖,只顯示前20個單詞,下面有一個helper函數。

# helper 函數,用於繪製最上面的單詞。
def plot_top_words(word_count_dict, show_top_n=20):
    word_count_table = pd.DataFrame.from_dict(word_count_dict, orient = 'index').rename(columns={0: 'score'})
    
    word_count_table.sort_values(by='score').tail(show_top_n).plot(kind='barh', figsize=(10,10))
    plt.show()

讓咱們展現前20個單詞。

plot_top_words(word_count, 20)

從上面的圖中,咱們能夠看到「ai」和「apple」兩個詞出如今頂部。這是有道理的,由於這篇文章是關於蘋果收購一家人工智能初創公司的。

(7) 根據分數排列句子

如今,咱們將根據句子得分對每一個句子的重要性進行排序。咱們將:

  • 刪除超過30個單詞的句子,認識到長句未必老是有意義的;

  • 而後,從構成句子的每一個單詞中加上分數,造成句子分數。

高分的句子將排在前面。前面的句子將造成咱們的總結。

注意:根據個人經驗,任何25到30個單詞均可以給你一個很好的總結。

# 建立空字典來存儲句子分數
sentence_score = {}

# 循環經過標記化的句子,只取少於30個單詞的句子,而後加上單詞分數來造成句子分數
for sentence in sentences:
    # 檢查句子中的單詞是否在字數字典中
    for word in nltk.word_tokenize(sentence.lower()):
        if word in word_count.keys():
            # 只接受少於30個單詞的句子
            if len(sentence.split(' ')) < 30:
                # 把單詞分數加到句子分數上
                if sentence not in sentence_score.keys():
                    sentence_score[sentence] = word_count[word]
                else:
                    sentence_score[sentence] += word_count[word]

咱們將句子-分數字典轉換成一個數據框,並顯示sentence_score

注意:字典不容許根據分數對句子進行排序,所以須要將字典中存儲的數據轉換爲DataFrame。

df_sentence_score = pd.DataFrame.from_dict(sentence_score, orient = 'index').rename(columns={0: 'score'})
df_sentence_score.sort_values(by='score', ascending = False)

(8) 選擇前面的句子做爲摘要

咱們使用堆隊列算法來選擇前3個句子,並將它們存儲在best_quences變量中。

一般3-5句話就足夠了。根據文檔的長度,能夠隨意更改要顯示的最上面的句子數。

在本例中,我選擇了3,由於咱們的文本相對較短。

# 展現最好的三句話做爲總結         
best_sentences = heapq.nlargest(3, sentence_score, key=sentence_score.get)

讓咱們使用print和for loop函數顯示摘要文本。

print('SUMMARY')
print('------------------------')

# 根據原文中的句子順序顯示最上面的句子
for sentence in sentences:
    if sentence in best_sentences:
        print (sentence)

這是到個人Github的連接以獲取Jupyter筆記本。你還將找到一個可執行的Python文件,你能夠當即使用它來總結你的文本:https://github.com/louisteo9/personal-text-summarizer

讓咱們看看算法的實際操做!

如下是一篇題爲「蘋果以5000萬美圓收購人工智能創業公司(Apple Acquire AI Startup)以推動其應用程序」的新聞文章的原文(原文可在此處找到):https://analyticsindiamag.com/apple-acquires-ai-startup-for-50-million-to-advance-its-apps/

In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.

Reported by Bloomberg, the AI startup — Vilynx is headquartered in Barcelona, which is known to build software using computer vision to analyse a video’s visual, text, and audio content with the goal of 「understanding」 what’s in the video. This helps it categorising and tagging metadata to the videos, as well as generate automated video previews, and recommend related content to users, according to the company website.

Apple told the media that the company typically acquires smaller technology companies from time to time, and with the recent buy, the company could potentially use Vilynx’s technology to help improve a variety of apps. According to the media, Siri, search, Photos, and other apps that rely on Apple are possible candidates as are Apple TV, Music, News, to name a few that are going to be revolutionised with Vilynx’s technology.

With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.

The purchase will also advance Apple’s AI expertise, adding up to 50 engineers and data scientists joining from Vilynx, and the startup is going to become one of Apple’s key AI research hubs in Europe, according to the news.

Apple has made significant progress in the space of artificial intelligence over the past few months, with this purchase of UK-based Spectral Edge last December, Seattle-based Xnor.ai for $200 million and Voysis and Inductiv to help it improve Siri. With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space. In 2018, CEO Tim Cook said in an interview that the company had bought 20 companies over six months, while only six were public knowledge.

摘要以下:

SUMMARY
------------------------
In an attempt to scale up its AI portfolio, Apple has acquired Spain-based AI video startup — Vilynx for approximately $50 million.
With CEO Tim Cook’s vision of the potential of augmented reality, the company could also make use of AI-based tools like Vilynx.
With its habit of quietly purchasing smaller companies, Apple is making a mark in the AI space.

結尾

祝賀你!你已經在Python中建立了你的我的文本摘要器。我但願,摘要看起來很不錯。

原文連接:https://towardsdatascience.com/report-is-too-long-to-read-use-nlp-to-create-a-summary-6f5f7801d355

歡迎關注磐創AI博客站:
http://panchuang.net/

sklearn機器學習中文官方文檔:
http://sklearn123.com/

歡迎關注磐創博客資源彙總站:
http://docs.panchuang.net/

相關文章
相關標籤/搜索