Tokenizzazione e rimozione delle stop word
Suddivida il testo in token e filtri le parole poco informative con anti_join()
Tokenizzazione e rimozione delle stop word è una lezione R Academy gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento R Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso R Academy include 4 lezioni in totale.
Che cos'è il text mining?
Il text mining (o analisi dei testi) trasforma il testo non strutturato in dati strutturati che possono essere analizzati statisticamente. Il pacchetto tidytext consente un approccio tidy: ogni riga rappresenta un token (parola, bigramma, frase), rendendo i dati compatibili con dplyr e ggplot2.
library(tidytext)
library(dplyr)
# A simple text corpus
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog.',
'Text mining with R is powerful and fun.',
'Natural language processing enables many applications.'
)
)
cat('Input: ', nrow(text_df), 'documents\n')
cat('Columns:', names(text_df), '\n')unnest_tokens: tokenizzazione delle parole
unnest_tokens(output, input) suddivide il testo in un formato con una riga per ogni token. Per impostazione predefinita, esegue la tokenizzazione per parola, converte il testo in minuscolo e rimuove la punteggiatura. L'argomento token supporta 'words', 'ngrams', 'sentences' e altro.
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:2,
text = c(
'R is a great language for data analysis.',
'Text mining reveals hidden patterns in documents.'
)
)
# Tokenise into words
tokens <- text_df |>
unnest_tokens(word, text)
cat('Tokens extracted:', nrow(tokens), '\n')
print(tokens)Il dataset stop_words
tidytext include un tibble integrato, stop_words, contenente 1.149 stop word inglesi comuni provenienti da tre lessici: SMART, Snowball e onix. Queste parole ("the", "is", "and"…) hanno poco significato semantico e vengono in genere rimosse prima dell'analisi.
library(tidytext)
library(dplyr)
# Inspect the stop_words dataset
cat('Total stop words:', nrow(stop_words), '\n')
cat('Lexicons:', paste(unique(stop_words$lexicon), collapse = ', '), '\n')
# First few stop words from each lexicon
stop_words |>
group_by(lexicon) |>
slice_head(n = 3) |>
print()anti_join: rimozione delle stop word
anti_join(tokens, stop_words, by = 'word') rimuove tutte le righe la cui word corrisponde a una voce di stop_words. Questo è il modello standard di tidytext per rimuovere le stop word: semplice, leggibile e facilmente estendibile.
library(tidytext)
library(dplyr)
text_df <- tibble::tibble(
doc_id = 1:3,
text = c(
'The quick brown fox jumps over the lazy dog',
'A stitch in time saves nine important words',
'To be or not to be that is the question'
)
)
tokens <- text_df |>
unnest_tokens(word, text)
cat('Before removing stop words:', nrow(tokens), '\n')
tokens_clean <- tokens |>
anti_join(stop_words, by = 'word')
cat('After removing stop words:', nrow(tokens_clean), '\n')
print(tokens_clean)count: frequenza dei termini
Dopo aver eseguito la tokenizzazione e rimosso le stop word, utilizzare count(word, sort = TRUE) per calcolare la frequenza dei termini. È il punto di partenza di molte analisi di text mining: le parole significative più frequenti caratterizzano gli argomenti del documento.
library(tidytext)
library(dplyr)
# Use Jane Austen's novels from janeaustenr package
# For demo: simulate a small corpus
corpus <- tibble::tibble(
text = c(
'data science involves statistics programming analysis',
'machine learning algorithms data patterns training',
'statistics probability distributions random variables data',
'programming languages python r julia statistics',
'analysis patterns distributions algorithms science'
)
)
word_counts <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE)
cat('Top 8 words:\n')
print(head(word_counts, 8))Stop word personalizzate
I corpora specifici di un dominio contengono spesso parole ad alta frequenza ma irrilevanti (ad esempio "patient" e "doctor" nelle note mediche). Creare un tibble di stop word personalizzate e unirlo al lessico integrato utilizzando bind_rows().
library(tidytext)
library(dplyr)
# Domain-specific words to remove
custom_stops <- tibble::tibble(
word = c('data', 'analysis', 'r', 'using', 'also'),
lexicon = 'custom'
)
# Combine with built-in stop words
all_stops <- bind_rows(stop_words, custom_stops)
cat('Total stop words after custom:', nrow(all_stops), '\n')
corpus <- tibble::tibble(
text = c(
'Using R for data analysis and machine learning models',
'Statistical data analysis also involves data visualisation'
)
)
clean_tokens <- corpus |>
unnest_tokens(word, text) |>
anti_join(all_stops, by = 'word') |>
count(word, sort = TRUE)
print(clean_tokens)Tokenizzazione dei bigrammi
Impostare token = 'ngrams', n = 2 per eseguire la tokenizzazione in coppie consecutive di parole (bigrammi). I bigrammi catturano espressioni come "machine learning" o "data science" che le singole parole non riescono a rappresentare, fornendo un contesto più ricco.
library(tidytext)
library(dplyr)
corpus <- tibble::tibble(
doc_id = 1:2,
text = c(
'machine learning and deep learning are powerful techniques',
'natural language processing uses machine learning methods'
)
)
bigrams <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2)
cat('Bigrams extracted:', nrow(bigrams), '\n')
print(bigrams)
# Count most common bigrams
bigram_counts <- bigrams |> count(bigram, sort = TRUE)
cat('\nTop bigrams:\n')
print(head(bigram_counts, 5))Filtrare i bigrammi per migliorarne la qualità
I bigrammi più frequenti includono coppie di stop word come "of the". Separare il bigramma in due colonne con tidyr::separate(), filtrare le righe in cui una delle due parole è una stop word, quindi riunire le parole per ottenere coppie di termini significative.
library(tidytext)
library(dplyr)
library(tidyr)
corpus <- tibble::tibble(
text = c(
'the field of machine learning and deep learning is growing',
'natural language processing is a subfield of artificial intelligence'
)
)
bigrams_filtered <- corpus |>
unnest_tokens(bigram, text, token = 'ngrams', n = 2) |>
separate(bigram, into = c('word1', 'word2'), sep = ' ') |>
filter(
!word1 %in% stop_words$word,
!word2 %in% stop_words$word
) |>
unite(bigram, word1, word2, sep = ' ') |>
count(bigram, sort = TRUE)
print(bigrams_filtered)Visualizzare le frequenze delle parole
Rappresentare le frequenze delle parole con un grafico a barre utilizzando ggplot2. Ordinare le barre con reorder(word, n) e utilizzare coord_flip() per ottenere etichette orizzontali. È uno degli output più efficaci per comunicare i risultati del text mining.
library(tidytext)
library(dplyr)
library(ggplot2)
corpus <- tibble::tibble(
text = c(
'statistics probability machine learning algorithms patterns',
'data science programming analysis visualisation models',
'machine learning deep learning neural networks patterns',
'probability statistics hypothesis testing distributions',
'algorithms optimisation gradient descent models training'
)
)
top_words <- corpus |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
slice_head(n = 10)
ggplot(top_words, aes(reorder(word, n), n)) +
geom_col(fill = 'steelblue') +
coord_flip() +
labs(x = 'Word', y = 'Count', title = 'Top 10 Terms') +
theme_minimal()Conteggi delle parole per documento
Quando il corpus contiene più documenti, aggiungere una colonna con l'identificatore del documento e raggruppare per doc_id, word per calcolare le frequenze dei termini per documento. Questo risultato alimenta direttamente le analisi TF-IDF e i modelli degli argomenti.
library(tidytext)
library(dplyr)
docs <- tibble::tibble(
doc_id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
text = c(
'machine learning models training',
'neural networks deep learning',
'algorithms gradient descent optimisation',
'statistical analysis probability distributions',
'hypothesis testing confidence intervals regression',
'bayesian inference prior posterior likelihood',
'data visualisation plots charts dashboards',
'ggplot2 ggvis plotly interactive graphics',
'colour scales aesthetics themes layers'
)
)
word_counts <- docs |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(doc_id, word, sort = TRUE)
cat('Word-doc pairs:', nrow(word_counts), '\n')
print(head(word_counts, 10))Tokenizzazione delle frasi
Impostare token = 'sentences' per suddividere il testo in corrispondenza dei confini tra le frasi. I token a livello di frase sono utili per l'analisi del sentiment (assegnare un punteggio a ogni frase), la sintesi (selezionare le frasi rappresentative) e le attività di domanda e risposta.
library(tidytext)
library(dplyr)
doc <- tibble::tibble(
id = 1L,
text = paste(
'R is a statistical programming language.',
'It is widely used in data science and machine learning.',
'The tidyverse makes data manipulation easy.',
'Text mining with tidytext is elegant and powerful.'
)
)
sentences <- doc |>
unnest_tokens(sentence, text, token = 'sentences')
cat('Sentences found:', nrow(sentences), '\n')
print(sentences$sentence)Verifica rapida
È stata eseguita la tokenizzazione di un corpus in parole utilizzando unnest_tokens() e si desidera rimuovere le parole inglesi comuni. Quale operazione consente di farlo utilizzando il dataset integrato stop_words?
Riepilogo: tokenizzazione e stop word
Concetti chiave:
unnest_tokens(word, text)converte il testo grezzo in un formato tidy con una riga per ogni parola- Impostazione predefinita: testo in minuscolo e punteggiatura rimossa; supporta
'words','ngrams','sentences' stop_wordsè un tibble integrato con 1.149 parole inglesi comuni provenienti da 3 lessicianti_join(tokens, stop_words, by = 'word')rimuove le stop word- Combinare con
bind_rows()per aggiungere stop word personalizzate specifiche del dominio count(word, sort = TRUE)calcola la frequenza dei termini a partire dai token tidy- Bigrammi:
unnest_tokens(bigram, text, token = 'ngrams', n = 2)
library(tidytext)
library(dplyr)
tibble::tibble(text = 'The quick brown fox jumps over the lazy dog') |>
unnest_tokens(word, text) |>
anti_join(stop_words, by = 'word') |>
count(word, sort = TRUE) |>
print()Impara R con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 43
- Lezioni
- 159
Domande Frequenti
La lezione «Tokenizzazione e rimozione delle stop word» è gratuita?
Sì — il testo completo di «Tokenizzazione e rimozione delle stop word» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso R Academy, passa a CoddyKit PRO. Il corso R Academy include 4 lezioni in totale.
Cosa imparerò in «Tokenizzazione e rimozione delle stop word»?
Suddivida il testo in token e filtri le parole poco informative con anti_join() Eserciti R Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare R Academy?
Non è richiesta alcuna esperienza precedente. R Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Tokenizzazione e rimozione delle stop word»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione R Academy?
Sì. Ogni lezione R Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Tokenizzazione e rimozione delle stop word
- TF-IDF e analisi della frequenza dei termini
- Analisi del sentiment in R
- Topic modeling con LDA