ekphrasis

repository·master·Indexed 20 days ago

https://github.com/cbaziotis/ekphrasis

A lightweight text processing library designed for social media text. It provides specialized tools for tokenization via SocialTokenizer, hashtag segmentation using the Segmenter class, and spell correction via SpellCorrector. The library includes a TextPreProcessor for building cleaning and normalization pipelines, and supports custom word statistics generation for domain-specific corpora.

Tokens
2.9K
Snippets
8
Records
9
Agent score
22%

What's inside ekphrasis

  1. Overview of ekphrasis functionality

    master

    ekphrasis is a collection of lightweight text tools specifically designed for social network text (e.g., Twitter, Facebook). Its core capabilities include:

    1. Social Tokenizer: A tokenizer that handles complex emoticons, emojis, dates, times, and other unstructured expressions common in social media.
    2. Word Segmentation: Splits long strings into constituent words, which is particularly useful for segmenting hashtags.
    3. Spell Correction: Replaces misspelled words with the most probable candidates based on word statistics.
    4. Customization:
      • Word Statistics: Segmentation and Spell Correction rely on word statistics. While Wikipedia and Twitter corpora are provided, you can generate statistics from your own domain-specific corpus (e.g., biomedical text) to prevent domain-specific terms from being flagged as misspellings.
      • Entity Identification: You can identify new entities by adding regular expressions to ekphrasis/regexes/expressions.txt.
    5. Pre-Processing Pipeline: A way to combine tokenization, normalization, word annotation (labeling), and other steps into a single workflow for preparing datasets for machine learning or analysis.
  2. Install ekphrasis

    master

    You can install ekphrasis either from PyPI or directly from the GitHub source repository.

    To install the latest version from PyPI:

    pip install ekphrasis -U

    To build and install from the GitHub source:

    pip install git+git://github.com/cbaziotis/ekphrasis.git
  3. Perform sentiment analysis with TextPreProcessor and polarity

    master

    You can build a sentiment analysis pipeline by combining TextPreProcessor for text cleaning and tokenization with the polarity utility to calculate sentiment scores.

    1. Initialize TextPreProcessor with desired cleaning options (e.g., fix_text=True, unpack_contractions=True) and a tokenizer function.
    2. Use pre_process_docs() to transform a list of raw strings into tokenized lists.
    3. Pass the resulting tokens to polarity(sent) to obtain a sentiment polarity score and a dictionary of detailed scores.
    from ekphrasis.classes.preprocessor import TextPreProcessor
    from ekphrasis.classes.tokenizer import SocialTokenizer
    from ekphrasis.utils.nlp import polarity
    
    sentences = [
        "So there is no way for me to plug it in here in the US unless I go by a converter.",
        "Good case, Excellent value.",
        "Works great!",
        'The design is very odd, as the ear "clip" is not very comfortable at all.',
        "Needless to say, I wasted my money."
    ]
    
    # define preprocessing pipeline
    text_processor = TextPreProcessor(
        fix_text=True,
        unpack_contractions=True,
        tokenizer=SocialTokenizer(lowercase=True).tokenize,
    )
    
    # pass each sentence through the pipeline
    tokenized_sentences = list(text_processor.pre_process_docs(sentences))
    for sent in tokenized_sentences:
        _polarity, _scores = polarity(sent)
        print("{:.4f}\t".format(_polarity) + " ".join(sent))
  4. Use SocialTokenizer for social media text

    master

    The SocialTokenizer is designed to handle the complexities of social media text, such as emoticons, emojis, hashtags, and censored words, without incorrectly splitting them. It is particularly useful for sentiment analysis tasks where preserving these expressions is critical.

    To use it, instantiate SocialTokenizer and call its .tokenize method. You can pass lowercase=True or False to the constructor.

    Example comparison with standard tokenizers:

    • Whitespace Tokenizer: Splits only on spaces.
    • WordPunct Tokenizer: Splits on all punctuation.
    • SocialTokenizer: Keeps complex expressions like >3:/ or #TwinPeaks intact while handling punctuation appropriately.
    from ekphrasis.classes.tokenizer import SocialTokenizer
    
    social_tokenizer = SocialTokenizer(lowercase=False).tokenize
    sentence = "#TwinPeaks \(^o^)/ yaaaay!!!"
    print(social_tokenizer(sentence))
  5. Perform word segmentation with Segmenter

    master

    The Segmenter uses the Viterbi algorithm to split concatenated words (e.g., hashtags or compound words) into individual tokens. It requires a corpus to provide word statistics.

    Available built-in corpora:

    • english: English Wikipedia statistics.
    • twitter: Twitter message statistics.
    • Custom: Any corpus name you have generated using generate_stats.py.

    Note: The algorithm also automatically splits words based on CamelCase or PascalCase.

    Usage:

    1. Instantiate Segmenter(corpus="<corpus_name>").
    2. Call .segment("<string>").
    from ekphrasis.classes.segmenter import Segmenter
    
    # Using built-in Twitter statistics
    seg_tw = Segmenter(corpus="twitter")
    print(seg_tw.segment("gamedev")) # Output: ['game', 'dev']
    
    # Using CamelCase splitting
    seg = Segmenter()
    print(seg.segment("camelCased")) # Output: ['camel', 'cased']
  6. Perform spell correction with SpellCorrector

    master

    The SpellCorrector uses word statistics to find the most probable candidate for a misspelled word. It is based on Peter Norvig's spell-corrector.

    Usage:

    1. Instantiate SpellCorrector(corpus="<corpus_name>").
    2. Call .correct("<word>").

    Available corpora include english and twitter.

    from ekphrasis.classes.spellcorrect import SpellCorrector
    
    sp = SpellCorrector(corpus="english")
    print(sp.correct("korrect")) # Output: 'correct'
  7. Define a text pre-processing pipeline with TextPreProcessor

    master

    Use the TextPreProcessor class to create a comprehensive pipeline for cleaning and normalizing social media text. The processor can handle normalization of specific terms (like URLs or emails), annotation of features (like hashtags or all-caps words), HTML fixing, word segmentation for hashtags, contraction unpacking, and spell correction.

    Key configuration options:

    • normalize: A list of term types to normalize (e.g., ['url', 'email', 'percent', 'money', 'phone', 'user', 'time', 'date', 'number']).
    • annotate: A set of feature types to annotate (e.g., {'hashtag', 'allcaps', 'elongated', 'repeated', 'emphasis', 'censored'}).
    • fix_html: Boolean to fix HTML tokens.
    • segmenter: The corpus to use for word segmentation (e.g., 'twitter').
    • corrector: The corpus to use for spell correction (e.g., 'twitter').
    • unpack_hashtags: Boolean to perform word segmentation on hashtags.
    • unpack_contractions: Boolean to expand contractions (e.g., can't -> can not).
    • spell_correct_elong: Boolean to enable spell correction for elongated words.
    • tokenizer: A callable that takes a string and returns a list of tokens (e.g., SocialTokenizer(lowercase=True).tokenize).
    • dicts: A list of dictionaries used for replacing specific tokens with other expressions (e.g., emoticons).
    from ekphrasis.classes.preprocessor import TextPreProcessor
    from ekphrasis.classes.tokenizer import SocialTokenizer
    from ekphrasis.dicts.emoticons import emoticons
    
    text_processor = TextPreProcessor(
        normalize=['url', 'email', 'percent', 'money', 'phone', 'user', 'time', 'url', 'date', 'number'],
        annotate={'hashtag', 'allcaps', 'elongated', 'repeated', 'emphasis', 'censored'},
        fix_html=True,
        segmenter="twitter",
        corrector="twitter",
        unpack_hashtags=True,
        unpack_contractions=True,
        spell_correct_elong=False,
        tokenizer=SocialTokenizer(lowercase=True).tokenize,
        dicts=[emoticons]
    )
    
    sentences = ["CANT WAIT for the new season of #TwinPeaks \(^o^)/!!!"]
    for s in sentences:
        print(" ".join(text_processor.pre_process_doc(s)))
  8. Perform word segmentation with the Segmenter class

    master

    The Segmenter class is used to split concatenated words (like hashtags or compound words) into their constituent tokens. You can initialize a Segmenter by specifying a corpus to define the statistical model used for segmentation. Supported corpus options include:

    • "english": General English corpus.
    • "twitter": Corpus optimized for social media text.
    • "text8": Corpus based on the text8 dataset.

    Use the .segment(word) method to process a single string and return the segmented tokens.

    from ekphrasis.classes.segmenter import Segmenter
    
    # Initialize segmenters with different corpora
    seg_eng = Segmenter(corpus="english")
    seg_tw = Segmenter(corpus="twitter")
    seg_t8 = Segmenter(corpus="text8")
    
    # Segment a single word
    word = "smallandinsignificant"
    print(seg_eng.segment(word))
  9. Generate custom word statistics for segmentation and spell correction

    master

    The segmentation and spell correction tools require word statistics (unigrams and bigrams). While ekphrasis provides statistics for English Wikipedia and Twitter, you can generate your own using the generate_stats.py script.

    Run the script against a text file or a directory of files:

    python generate_stats.py --input <path> --name <corpus_name> --ngrams <n> --mincount <unigram_min> <bigram_min>

    Arguments:

    • --input: Path to the file or directory containing text files.
    • --name: The name of the corpus (this will create a directory in ekphrasis/stats/<name>/).
    • --ngrams: The maximum number of n-grams to calculate.
    • --mincount: The minimum frequency required for an n-gram to be included (provide two values: one for unigrams and one for bigrams).
    python generate_stats.py --input text8.txt --name text8 --ngrams 2 --mincount 70 30