Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีดึง synonyms/antonyms จาก NLTK WordNet ใน Python

WordNet เป็นส่วนหนึ่งของ Natural Language Toolkit ของ Python เป็นฐานข้อมูลคำศัพท์ขนาดใหญ่ของคำว่า Nouns, Adjectives, Adverbs และ Verbs ภาษาอังกฤษ พวกมันถูกจัดกลุ่มเป็นชุดของ cognitive synonyms เรียกว่า synsets

เพื่อใช้ WordNet ต้อง install โมดูล NLTK ก่อน แล้วดาวน์โหลด WordNet package

$ sudo pip3 install nltk
$ python3
>>> import nltk
>>> nltk.download('wordnet')

ใน wordnet มีกลุ่มคำบางกลุ่มที่ความหมายเหมือนกัน

ในตัวอย่างแรก เราจะดูว่า wordnet คืนค่าความหมายและรายละเอียดอื่นๆ ของคำอย่างไร บางครั้งถ้ามีตัวอย่าง อาจให้ตัวอย่างมาด้วย

ตัวอย่างโค้ด

from nltk.corpus import wordnet
synset = wordnet.synsets("Travel")
print('Word and Type: ' + synset[0].name())
print('Synonym of Travel is: ' + synset[0].lemmas()[0].name())
print('The meaning of the word: ' + synset[0].definition())
print('Example of Travel: ' + str(synset[0].examples()))

ผลลัพธ์

Word and Type: travel.n.01
Synonym of Travel is: travel
The meaning of the word: the act of going from one place to another
Example of Travel: ['he enjoyed selling but he hated the travel']

ในตัวอย่างก่อนหน้า เราได้รายละเอียดของคำบางคำ ที่นี่เราจะดูว่า wordnet ส่ง synonyms และ antonyms ของคำที่ให้มาได้อย่างไร

ตัวอย่างโค้ด

import nltk
from nltk.corpus import wordnet

syn = list()
ant = list()
for synset in wordnet.synsets("Worse"):
    for lemma in synset.lemmas():
        syn.append(lemma.name())  # เพิ่ม synonyms
        if lemma.antonyms():  # เมื่อมี antonyms เพิ่มลงลิสต์
            ant.append(lemma.antonyms()[0].name())

print('Synonyms: ' + str(syn))
print('Antonyms: ' + str(ant))

ผลลัพธ์

Synonyms: ['worse', 'worse', 'worse', 'worsened', 'bad', 'bad', 'big', 'bad', 'tough', 'bad', 'spoiled', 'spoilt', 'regretful', 'sorry', 'bad', 'bad', 'uncollectible', 'bad', 'bad', 'bad', 'risky', 'high-risk', 'speculative', 'bad', 'unfit', 'unsound', 'bad', 'bad', 'bad', 'forged', 'bad', 'defective', 'worse']
Antonyms: ['better', 'better', 'good', 'unregretful']

NLTK wordnet มีคุณสมบัติยอดเยี่ยมอีกอย่าง ด้วยมันเราสามารถตรวจสอบว่าสองคำใกล้เคียงกันหรือไม่ จะคืนค่า similarity ratio จากคู่คำ

ตัวอย่างโค้ด

import nltk
from nltk.corpus import wordnet

first_word = wordnet.synset("Travel.v.01")
second_word = wordnet.synset("Walk.v.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))

first_word = wordnet.synset("Good.n.01")
second_word = wordnet.synset("zebra.n.01")
print('Similarity: ' + str(first_word.wup_similarity(second_word)))

ผลลัพธ์

Similarity: 0.6666666666666666
Similarity: 0.09090909090909091