Random Document Analysis with spaCy and Displacy

  • Share this:

Code introduction


This function uses the spaCy library to load a random model, then processes a randomly chosen document, and finally visualizes the dependency parse of the document using the displacy library.


Technology Stack : spaCy, displacy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import spacy
from spacy import displacy
import random

def analyze_random_doc():
    # Load a random spaCy model
    nlp = spacy.load(random.choice(['en_core_web_sm', 'en_core_web_md', 'en_core_web_lg']))

    # Randomly choose a document to analyze
    text = random.choice([
        "The quick brown fox jumps over the lazy dog.",
        "Natural language processing is a subfield of linguistics.",
        "Machine learning is a field of study that gives computers the ability to learn without being explicitly programmed."
    ])

    # Process the text
    doc = nlp(text)

    # Visualize the dependency parse of the document
    displacy.render(doc, style='dep', jupyter=True)

    return doc                
              
Tags: