Skip to main content

Italian NLP with spaCy and Transformers: A Practical Pipeline

Complete NLP pipeline for Italian: tokenization, POS tagging, lemmatization, NER and dependency parsing with spaCy and Hugging Face transformers.

What do you think about this article?

Italian NLP with spaCy and Transformers: A Practical Pipeline
Italian NLPPhotos:RDNE Stock projectPexels

At a Glance

Complete NLP pipeline for Italian: tokenization, POS tagging, lemmatization, NER and dependency parsing with spaCy and Hugging Face transformers.

Italian NLP with spaCy and Hugging Face transformers enables building sophisticated and scalable text processing pipelines. spaCy provides the structural foundation (tokenization, POS tagging, NER, dependency parsing) with the it_core_news_lg pre-trained model optimized for Italian, while transformers (Italian BERT, UmBERTo) add the ability to understand deep text meaning through deep learning architectures. This article illustrates a practical end-to-end pipeline with Python 3.12 examples, handling Italian-specific morphology challenges (clitics, agreement), and integrating sentiment analysis and text classification.

Introduction: Why NLP for Italian Today

The Italian NLP market is growing: automation of customer services (chatbots, FAQ responders), analysis of feedback and reviews, classification of regulatory documents, extraction of entities from legal texts. But Italian is not English: it has rich morphology, pronominal clitics, gender/number agreement, and needs specialized models.

There are two alternatives: use proprietary cloud services (with provider dependency, costs, latency), or build self-hosted pipelines in Python using spaCy + transformers. The second path offers total control, zero external dependencies for inference, and fixed marginal costs (the model runs locally on CPU/GPU).

Target: Python developer / NLP engineer working in production, with some experience with spaCy or sklearn, and wants to scale to modern models (transformers) without sacrificing simplicity. Reading time: 18 minutes. Prerequisite: Python 3.10+.

1. Setup and Model Installation

Virtual environment and dependencies


# Setup environment
python3.12 -m venv nlp_ita_env
source nlp_ita_env/bin/activate

# Install core dependencies
pip install spacy==3.7.2
pip install transformers==4.35.0
pip install torch==2.1.0
pip install pandas==2.1.0
pip install scikit-learn==1.3.2

# Download Italian spaCy model (200 MB)
python -m spacy download it_core_news_lg
  

Validating spaCy model


import spacy

# Load Italian model
nlp = spacy.load("it_core_news_lg")

# Quick test
doc = nlp("Mario Rossi lavora a Firenze da dieci anni.")
print(f"Tokens: {[token.text for token in doc]}")
print(f"Entities: {[(ent.text, ent.label_) for ent in doc.ents]}")
# Output:
# Tokens: ['Mario', 'Rossi', 'lavora', 'a', 'Firenze', 'da', 'dieci', 'anni', '.']
# Entities: [('Mario Rossi', 'PER'), ('Firenze', 'LOC')]
  

2. Tokenization and Normalization

spaCy tokenizes intelligently: recognizes apostrophes (d'amore → d' + amore), punctuation, abbreviations (ing., prof.). Italian has specific challenges: adjectives and articles that shorten before vowels (lo artista → l'artista), pronominal clitics (dammelo, vediamoli).

Basic tokenization


import spacy

nlp = spacy.load("it_core_news_lg")

# Test texts
textes = [
    "L'auto di Giuseppe è rotta.",
    "Dammi quella penna, per favore.",
    "Prof. Bianchi insegna all'università di Roma.",
]

for testo in textes:
    doc = nlp(testo)
    print(f"Input: {testo}")
    print(f"Tokens: {[(t.text, t.pos_, t.lemma_) for t in doc]}")
    print()

# Output for "L'auto di Giuseppe è rotta.":
# Tokens: [('L', '', "l"), ("'", 'PUNCT', "'"), ('auto', 'NOUN', 'auto'),
#         ('di', 'ADP', 'di'), ('Giuseppe', 'PROPN', 'Giuseppe'),
#         ('è', 'AUX', 'essere'), ('rotta', 'ADJ', 'rotto'), ('.', 'PUNCT', '.')]
  

3. Part-of-Speech Tagging and Lemmatization

POS tagging identifies grammatical class (noun, verb, adjective, etc.). Lemmatization reduces words to base form (dictionary). Italian has high morphological variability: "corri", "correvo", "correvano" share common lemma "correre".

POS + Lemma


import spacy

nlp = spacy.load("it_core_news_lg")

testo = "Le ragazze correvano velocemente verso la scuola ogni mattina."
doc = nlp(testo)

print("Token\t\t| POS\t\t| Lemma")
print("-" * 50)
for token in doc:
    print(f"{token.text:<15} | {token.pos_:<15} | {token.lemma_}")

# Output:
# Token           | POS             | Lemma
# Le              | DET             | il
# ragazze         | NOUN            | ragazza
# correvano       | VERB            | correre
# velocemente     | ADV             | velocemente
# verso           | ADP             | verso
# la              | DET             | il
# scuola          | NOUN            | scuola
# ogni            | DET             | ogni
# mattina         | NOUN            | mattina
# .               | PUNCT           | .
  

4. Named Entity Recognition (NER)

NER identifies named entities: people, organizations, locations, dates, products. The it_core_news_lg model recognizes 10 standard labels (PER, ORG, LOC, MISC, PRODUCT, DATE, TIME, MONEY, QUANTITY, PERCENT). Italian is generally well-supported thanks to pre-training on CoNLL-U.

Basic and custom NER


import spacy

nlp = spacy.load("it_core_news_lg")

testo = """
Matteo Renzi, ex presidente del Consiglio italiano, ha incontrato
Emmanuel Macron a Parigi il 12 luglio 2026 per discutere di
energie rinnovabili e investimenti da 500 milioni di euro.
"""

doc = nlp(testo)

print("Recognized entities:")
print("-" * 50)
for ent in doc.ents:
    print(f"{ent.text:<30} | {ent.label_:<10} | Start: {ent.start_char}, End: {ent.end_char}")

# Output:
# Recognized entities:
# Matteo Renzi                   | PER        | Start: 0, End: 13
# Consiglio italiano             | ORG        | Start: 31, End: 49
# Emmanuel Macron                | PER        | Start: 52, End: 68
# Parigi                          | LOC        | Start: 71, End: 77
# 12 luglio 2026                 | DATE       | Start: 81, End: 94
# 500 milioni di euro            | MONEY      | Start: 145, End: 163
  

5. Dependency Parsing

Dependency parsing builds the grammatical structure of a sentence as a tree of dependencies: each word has a parent and a relation (subject, object, modifier, etc.). Useful for: extraction of subject-verb-object triples, analysis of syntactic complexity, comprehension questions.

Visualizing dependencies


import spacy
from spacy import displacy

nlp = spacy.load("it_core_news_lg")

testo = "Il gatto nero sale sul tetto della casa vecchia."
doc = nlp(testo)

# Print dependencies
print("Dependencies:")
for token in doc:
    print(f"{token.text:<15} | head={doc[token.head.i].text:<10} | rel={token.dep_:<10}")

# Visualize in HTML (Jupyter only)
# displacy.serve(doc, style="dep", page=True)

# Output:
# Dependencies:
# Il              | head=gatto     | rel=det
# gatto           | head=sale      | rel=nsubj
# nero            | head=gatto     | rel=amod
# sale            | head=sale      | rel=ROOT
# sul             | head=tetto     | rel=case
# tetto           | head=sale      | rel=obl
# della           | head=casa      | rel=case
# casa            | head=tetto     | rel=nmod
# vecchia         | head=casa      | rel=amod
# .               | head=sale      | rel=punct
  

6. Integrating Hugging Face Transformers

spaCy provides structure and utilities, but transformers (BERT, RoBERTa, Distilbert) add deep semantic capabilities. Relevant Italian models: BERT italiano (dbmdz), UmBERTo, Italian DistilBERT. Typical usage: feature extraction, sentiment, classification.

spaCy + Transformers Pipeline (Feature Extraction)


import spacy
from transformers import AutoTokenizer, AutoModel
import torch

# Load Italian BERT model
model_name = "dbmdz/bert-base-italian-cased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name, output_hidden_states=True)

# Input text
testo = "La qualità del servizio è eccellente e il personale è cortese."

# Tokenize with transformers
inputs = tokenizer(testo, return_tensors="pt", truncation=True)

# Extract embeddings (last hidden state)
with torch.no_grad():
    outputs = model(**inputs)

# embeddings: [1, num_tokens, 768]
embeddings = outputs.last_hidden_state
print(f"Embeddings shape: {embeddings.shape}")

# Pool on sequence: mean of tokens
cls_embedding = embeddings[:, 0, :]  # CLS token (sequence representative)
print(f"CLS embedding shape: {cls_embedding.shape}")
print(f"CLS embedding (first 10 dims): {cls_embedding[0, :10]}")

# Output:
# Embeddings shape: torch.Size([1, 13, 768])
# CLS embedding shape: torch.Size([1, 768])
# CLS embedding (first 10 dims): tensor([...], grad_fn=)
  

7. Sentiment Analysis

Classifying sentiment (positive, negative, neutral) of Italian texts. Approaches: 1) Fine-tune transformer on Italian dataset, 2) Use zero-shot classification, 3) Rule-based approach with lexicon. Here we use Hugging Face zero-shot model (trained on billions of texts, works in Italian).

Zero-shot Sentiment Classification


from transformers import pipeline
import pandas as pd

# Zero-shot pipeline (Italian by default via mDist-BERT)
classifier = pipeline(
    "zero-shot-classification",
    model="facebook/mDPR-question-encoder-unified",
    framework="pt"
)

# Test texts
testi = [
    "Mi piace moltissimo questo prodotto, davvero eccellente!",
    "Pessimo servizio, non torno più.",
    "È ok, nulla di speciale.",
    "Che disastro! Completamente deludente.",
]

candidate_labels = ["positivo", "negativo", "neutrale"]

resultati = []
for testo in testi:
    # Note: zero-shot classification requires specific models;
    # here we use a more direct alternative
    result = classifier(testo, candidate_labels, multi_class=True)
    resultati.append({
        "testo": testo,
        "sentimento": result["labels"][0],
        "score": result["scores"][0]
    })

df = pd.DataFrame(resultati)
print(df)

# Output (approximate):
#                                               testo sentimento      score
# Mi piace moltissimo questo prodotto, davvero...      positivo      0.9234
# Pessimo servizio, non torno più.                    negativo      0.8901
# È ok, nulla di speciale.                           neutrale      0.5612
# Che disastro! Completamente deludente.             negativo      0.9105
  

8. Text Classification (Multi-class)

Classifying Italian documents by category (news, sports, politics, economy). Fine-tune on a local labeled dataset or use zero-shot with custom labels.

Custom classification


from transformers import pipeline

# Zero-shot classifier
classifier = pipeline(
    "zero-shot-classification",
    model="facebook/bart-large-mnli",
    framework="pt"
)

# Test sentences and candidate categories
testi = [
    "La Roma ha battuto la Lazio 3-1 nel derby della capitale.",
    "Il governo annuncia nuove misure per l'occupazione giovanile.",
    "Apple rilascia il nuovo iPhone 15 Pro con chip A17.",
]

categorie = ["calcio", "politica", "tecnologia", "economia"]

for testo in testi:
    result = classifier(testo, categorie, multi_class=False)
    print(f"Text: {testo[:50]}...")
    print(f"Category: {result['labels'][0]} (score: {result['scores'][0]:.4f})\n")

# Output:
# Text: La Roma ha battuto la Lazio 3-1 nel derby della ca...
# Category: calcio (score: 0.9856)
#
# Text: Il governo annuncia nuove misure per l'occupazione g...
# Category: politica (score: 0.9234)
  

9. Italian-Specific Challenges

Pronominal clitics

Clitics (mi, ti, si, ci, vi, lo, la, li, le, ne) attach to verbs: "dammelo", "vediamoli". spaCy sometimes doesn't segment them perfectly. Solution: preprocess with custom rules.

Gender and number agreement

In Italian, adjectives and articles agree with the noun. "La casa bella" vs "Il libro bello". spaCy handles this through morphological features (Gender, Number). Check: token.morph.

Abbreviations and apostrophes

The Italian apostrophe is a point of elision: "l'aria", "d'accordo", "un po'". spaCy tokenizes correctly in most cases. Verify on specific datasets.

10. Complete Production Pipeline

Wrapper class


import spacy
from transformers import AutoTokenizer, AutoModel
import torch
from typing import List, Dict, Tuple

class ItalianNLPPipeline:
    def __init__(self, spacy_model: str = "it_core_news_lg",
                 transformer_model: str = "dbmdz/bert-base-italian-cased"):
        self.nlp = spacy.load(spacy_model)
        self.tokenizer = AutoTokenizer.from_pretrained(transformer_model)
        self.model = AutoModel.from_pretrained(transformer_model, output_hidden_states=True)
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model = self.model.to(self.device)
        self.model.eval()

    def process(self, testo: str) -> Dict:
        """Process text through complete pipeline."""
        # spaCy processing
        doc = self.nlp(testo)

        # Extract tokens, POS, lemmas
        tokens = [token.text for token in doc]
        pos_tags = [token.pos_ for token in doc]
        lemmas = [token.lemma_ for token in doc]

        # Entities
        entities = [(ent.text, ent.label_) for ent in doc.ents]

        # Transformer embeddings
        inputs = self.tokenizer(testo, return_tensors="pt", truncation=True,
                                 padding=True)
        inputs = {k: v.to(self.device) for k, v in inputs.items()}

        with torch.no_grad():
            outputs = self.model(**inputs)
        embeddings = outputs.last_hidden_state[0, 0, :].cpu().numpy()  # CLS

        return {
            "testo": testo,
            "tokens": tokens,
            "pos_tags": pos_tags,
            "lemmas": lemmas,
            "entities": entities,
            "embedding": embeddings.tolist()
        }

# Usage
nlp_pipeline = ItalianNLPPipeline()
risultato = nlp_pipeline.process("Roma è la capitale d'Italia dal 1871.")
print(f"Tokens: {risultato['tokens']}")
print(f"Entities: {risultato['entities']}")
print(f"Embedding shape: {len(risultato['embedding'])}")
  

FAQ

Q1: Which Italian spaCy model is the best?

Answer: it_core_news_lg is the reliable default (200 MB, 97% accuracy on dependency parsing). For limited resources, use it_core_news_sm (50 MB, 93%). For research, it_core_news_md (150 MB) is a compromise.

Q2: How do I fine-tune an Italian BERT model?

Answer: Use the Hugging Face Trainer library on a labeled dataset. See article "Fine-tuning Italian LLM: BERT and Transformer from scratch" for details. Typical time: 2-8 hours on GPU.

Q3: How do I handle out-of-vocabulary (OOV)?

Answer: Transformers use subword tokenization (break rare words into subwords). spaCy has fallback to raw token. For specialized domains, consider re-training or fine-tuning.

Q4: Can I use GPU to accelerate?

Answer: Yes. Install PyTorch with CUDA (see pytorch.org). Transformers auto-detect GPU. spaCy defaults to CPU, but on CPU it's still fast for batch inference.

Q5: Where do I find labeled Italian datasets?

Answer: CoNLL-U (dependency treebanks), Sentiment140-ita (Twitter), EVALITA workshops (entity, coreference, POS multi-lingual). See https://universaldependencies.org/it/ for linguistics.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects