自然語言中的語言解釋


如果您曾經與聊天機器人交談過並使用過語言翻譯工具,那麼您就會知道這些工具的工作方式與真人完全一樣。這是因為它們使用自然語言處理 (NLP) 技術來理解人類用於交流的自然語言。然而,這相當複雜,因為每種語言都有不同的性質和結構以及各種語境。

自然語言處理 (NLP) 使用多種技術來獲得儘可能接近自然語言的輸出。其中一些技術包括:

  • 詞形還原 - 這是一個將單詞還原到其詞根形式或詞素的過程。例如,單詞 bravery 將被還原到其基本形式 brave。

  • 分詞 - 這是一個將句子分解成稱為標記的單個單詞的過程。這些標記由演算法處理以提供有用的資料。

  • 詞幹提取 - 這是一個從單詞中去除字首和字尾的過程。例如,單詞 playing 透過去除字尾將被簡化為 play。

此外,自然語言處理 (NLP) 可用於許多方面,例如文字摘要、句子相似性、文字分類、根據關鍵詞生成文字和翻譯等。

示例 1

在這個示例中,我們將看到如何使用 NLP 基於情感對句子進行分類。為此,我們將使用 Python 的 nltk 模組中的 textblob 庫。

演算法

  • 步驟 1 - 匯入 NaiveBaiyeClassifier 和 textblob 模組。

  • 步驟 2 - 建立一個包含字串的測試集,其中每個字串都與其表示其情感的關鍵字相關聯。在這個示例中,我們直接使用字串 positive 表示積極情感,使用 negative 表示消極情感。

  • 步驟 3 - 建立 NBC 類的物件並將測試集傳遞給它。

  • 步驟 4 - 使用 classify() 方法傳遞字串並測試其情感。

#import NaiveBayesClassifier and textblob module
from textblob.classifiers import NaiveBayesClassifier as NBC
from textblob import TextBlob

#prepare the test_set with corresponding sentiment
test_set = [
               ('I am tired of this attitude.', 'Negative'),
               ('He is the worst person I know!', 'Negative'),
               ('Your marks were very poor in Chemistry.', 'Positive'),
               ('I love United Kingdom.', 'Positive'),
               ('This is a great movie.', 'Positive'),
               ("What a delicious treat!", 'Positive'),
               ('I do not like her at all.', 'Negative')]


#create an object of NBC Class
model = NBC(test_set) 

#pass the string to be tested
print(model.classify("This is the best website."))
print(model.classify("I do not like Java as much as Python."))

輸出

Positive
Negative

您可以在輸出中看到,NLP 的資料分類方法正確地評估了句子的情感。

示例 2

在這個示例中,我們將看到如何使用 NLP 技術識別語言。為此,我們將使用 Python 的 langdetect 庫。

演算法

  • 步驟 1 - 從 Python 的 langdetect 庫匯入 detect 模組。

  • 步驟 2 - 提供需要檢測其語言的文字。

  • 步驟 3 - 使用 detect 模組列印結果。

#import the detect module
from langdetect import detect as dt

#provide the strings to be tested 
example_one = "This is a nice language."
example_two = "comment allez-vous?"   #means how are you in French

#display the result
print(dt(example_one))
print(dt(example_two))

輸出

en
fr

您可以看到程式碼分別返回了英語和法語的程式碼 en 和 fr。

結論

儘管 NLP 並不總是提供精確的輸出,但它是一個非常強大的工具,在資料科學、人工智慧和機器學習領域得到廣泛應用。此外,由於它允許我們與計算機進行交流,它是一個非常有用的工具,使文盲和殘疾人士能夠參與技術。隨著當今資料量的激增,使用自然語言處理工具對於有效分析和利用資料非常重要。

更新於:2023年8月7日

80 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告