Home Backend Development Python Tutorial Introduction to Tokenization and WordNet Basics with Python and NLTK

Introduction to Tokenization and WordNet Basics with Python and NLTK

Aug 02, 2024 am 02:57 AM

Introdução à Tokenização e Básicos do WordNet com Python e NLTK

Natural language processing (NLP) is a fascinating field that combines linguistics and computing to understand, interpret, and manipulate human language. One of the most powerful tools for this is the Natural Language Toolkit (NLTK) in Python. In this text, we will explore the concepts of tokenization and the use of WordNet, a lexical base for the English language, which is widely used in NLP.

What is Tokenization?

Tokenization is the process of dividing text into smaller units, called tokens. These tokens can be words, phrases, or even individual characters. Tokenization is a crucial step in text processing because it allows algorithms to understand and analyze text more effectively.

For example, consider the phrase "Hello, world!". Tokenizing this sentence can result in three tokens: ["Hello", "," "world", "!"]. This division allows each part of the text to be analyzed individually, facilitating tasks such as sentiment analysis, machine translation and named entity recognition.

In NLTK, tokenization can be done in several ways. Let's see some practical examples.

Tokenizing Text in Sentences

Dividing text into sentences is the first step in many NLP tasks. NLTK makes this easy with the sent_tokenize function.

import nltk
from nltk.tokenize import sent_tokenize

texto = "Olá mundo! Bem-vindo ao tutorial de NLTK. Vamos aprender a tokenizar textos."
sentencas = sent_tokenize(texto, language='portuguese')
print(sentencas)
Copy after login
e

The result will be:

['Olá mundo!', 'Bem-vindo ao tutorial de NLTK.', 'Vamos aprender a tokenizar textos.']
Copy after login
e

Here, the text was divided into three sentences. This is useful for more detailed analysis where each sentence can be processed individually.

Tokenizing Sentences into Words

After dividing the text into sentences, the next step is usually to divide these sentences into words. NLTK's word_tokenize function is used for this.

from nltk.tokenize import word_tokenize

frase = "Olá mundo!"
palavras = word_tokenize(frase, language='portuguese')
print(palavras)
Copy after login
e

The result will be:

['Olá', 'mundo', '!']
Copy after login
e

Now we have each word and punctuation symbol as separate tokens. This is essential for tasks like word frequency analysis, where we need to count how many times each word appears in a text.

Using Regular Expressions for Tokenization

In some cases, you may want more personalized tokenization. Regular expressions (regex) are a powerful tool for this. NLTK provides the RegexpTokenizer class to create custom tokenizers.

from nltk.tokenize import RegexpTokenizer

tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize("Vamos aprender NLTK.")
print(tokens)
Copy after login
e

The result will be:

['Vamos', 'aprender', 'NLTK']
Copy after login
e

Here, we use a regular expression that selects only words made up of alphanumeric characters, ignoring punctuation.

Introduction to WordNet

WordNet is a lexical database that groups words into sets of synonyms called synsets, provides short, general definitions, and records various semantic relationships between these words. In NLTK, WordNet is used to find synonyms, antonyms, hyponyms and hypernyms, among other relationships.

To use WordNet, we need to import the wordnet module from NLTK.

from nltk.corpus import wordnet
Copy after login
e

Searching for Synsets

A synset, or set of synonyms, is a group of words that share the same meaning. To search for the synsets of a word, we use the synsets function.

sinonimos = wordnet.synsets("dog")
print(sinonimos)
Copy after login
e

The result will be a list of synsets that represent different meanings of the word "dog".

[Synset('dog.n.01'), Synset('frump.n.01'), Synset('dog.n.03'), Synset('cad.n.01'), Synset('frank.n.02'), Synset('pawl.n.01'), Synset('andiron.n.01')]
Copy after login
e

Each synset is identified by a name that includes the word, the part of speech (n for noun, v for verb, etc.), and a number that distinguishes different senses.

Definitions and Examples

We can get the definition and usage examples of a specific synset.

sinonimo = wordnet.synset('dog.n.01')
print(sinonimo.definition())
print(sinonimo.examples())
Copy after login
e

The result will be:

a domesticated carnivorous mammal (Canis familiaris) that typically has a long snout, an acute sense of smell, non-retractile claws, and a barking, howling, or whining voice
['the dog barked all night']
Copy after login
e

This gives us a clear understanding of the meaning and use of "dog" in this context.

Searching Synonyms and Antonyms

To find synonyms and antonyms of a word, we can explore synset lemmas.

sinonimos = []
antonimos = []

for syn in wordnet.synsets("good"):
    for lemma in syn.lemmas():
        sinonimos.append(lemma.name())
        if lemma.antonyms():
            antonimos.append(lemma.antonyms()[0].name())

print(set(sinonimos))
print(set(antonimos))
Copy after login
e

The result will be a list of synonyms and antonyms for the word "good".

{'skillful', 'proficient', 'practiced', 'unspoiled', 'goodness', 'good', 'dependable', 'sound', 'right', 'safe', 'respectable', 'effective', 'trade_good', 'adept', 'good', 'full', 'commodity', 'estimable', 'honorable', 'undecomposed', 'serious', 'secure', 'dear', 'ripe'}
{'evilness', 'evil', 'ill'}
Copy after login
e

Calculating Semantic Similarity

WordNet also allows you to calculate the semantic similarity between words. Similarity is based on the distance between synsets in the hyponym/hypernym graph.

from nltk.corpus import wordnet

cachorro = wordnet.synset('dog.n.01')
gato = wordnet.synset('cat.n.01')
similaridade = cachorro.wup_similarity(gato)
print(similaridade)
Copy after login
e

The result will be a similarity value between 0 and 1.

0.8571428571428571
Copy after login
e

This value indicates that "dog" and "cat" are quite similar semantically.

Filtrando Stopwords

Stopwords são palavras comuns que geralmente não adicionam muito significado ao texto, como "e", "a", "de". Remover essas palavras pode ajudar a focar nas partes mais importantes do texto. O NLTK fornece uma lista de stopwords para várias línguas.

from nltk.corpus import stopwords

stop_words = set(stopwords.words('portuguese'))
palavras = ["Olá", "mundo", "é", "um", "lugar", "bonito"]
palavras_filtradas = [w for w in palavras if not w in stop_words]
print(palavras_filtradas)
Copy after login

O resultado será:

['Olá', 'mundo', 'lugar', 'bonito']
Copy after login

Aqui, as stopwords foram removidas da lista original de palavras.

Aplicações Práticas

Análise de Sentimentos

A análise de sentimentos é uma aplicação comum de PLN onde o objetivo é determinar a opinião ou emoção expressa em um texto. Tokenização e o uso de WordNet são passos importantes nesse processo.

Primeiro, dividimos o texto em palavras e removemos as stopwords. Em seguida, podemos usar os synsets para entender melhor o contexto e a polaridade das palavras.

texto = "Eu amo programação em Python!"
palavras = word_tokenize(texto, language='portuguese')
palavras_filtradas = [w for w in palavras if not w in stop_words]

polaridade = 0
for palavra in palavras_filtradas:
    synsets = wordnet.synsets(palavra, lang='por')
    if synsets:
        for syn in synsets:
            polaridade += syn.pos_score() - syn.neg_score()

print("Polaridade do texto:", polaridade)
Copy after login

Nesse exemplo simplificado, estamos somando os scores positivos e negativos dos synsets das palavras filtradas para determinar a polaridade geral do texto.

Reconhecimento de Entidades Nomeadas

Outra aplicação é o reconhecimento de entidades nomeadas (NER), que identifica e classifica nomes de pessoas, organizações, locais, etc., em um texto.

import nltk
nltk.download('maxent_ne_chunker')
nltk.download('words')

frase = "Barack Obama foi o 44º presidente dos Estados Unidos."
palavras = word_tokenize(frase, language='portuguese')
tags = nltk.pos_tag(palavras)
entidades = nltk.ne_chunk(tags)
print(entidades)
Copy after login

O resultado será uma árvore que identifica "Barack Obama" como uma pessoa e "Estados Unidos" como um local.

Conclusão

Neste texto, exploramos os conceitos básicos de tokenização e uso do WordNet com a biblioteca NLTK em Python. Vimos como dividir textos em sentenças e palavras, como buscar sinônimos e antônimos, calcular similaridades semânticas, e aplicações práticas como análise de sentimentos e reconhecimento de entidades nomeadas. A NLTK é uma ferramenta poderosa para qualquer pessoa interessada em processamento de linguagem natural, oferecendo uma ampla gama de funcionalidades para transformar e analisar textos de forma eficaz.

The above is the detailed content of Introduction to Tokenization and WordNet Basics with Python and NLTK. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles