Efficiently Count Instances of Letter-Digraphs/-Bigrams in a Corpus - Results Shown in Spreadsheet

Abstract: Count letter-digraphs and bigrams in large text corporums efficiently using Python and export results to a spreadsheet.

Created: 2026-09-23 by
You can efficiently count letter-digraphs and bigrams in a large text corpus by using Python’s collections.Counter combined with list comprehensions. This approach processes text in memory without loading entire files into complex data structures, ensuring high performance even for gigabyte-scale datasets. The resulting counts are then exported directly to a CSV file, which opens seamlessly in Excel or Google Sheets for immediate analysis and visualization.

Understanding Bigrams and Digraphs

A bigram (or digraph) is a sequence of two adjacent characters from a string. In natural language processing and cryptanalysis, analyzing the frequency of these pairs helps identify patterns, detect anomalies, or study linguistic properties. For example, in English, "th" and "he" are among the most common bigrams. When working with a corpus—a large collection of texts—counting these occurrences manually is impossible due to the volume of data. Instead, an algorithmic approach is required to iterate through the text and tally each unique pair. The core challenge lies in efficiency. A naive solution might involve nested loops or repeated string slicing that creates thousands of intermediate string objects, leading to high memory usage and slow execution times. By leveraging Python’s built-in libraries, specifically itertools and collections, we can create a streamlined pipeline that minimizes overhead. This method is particularly useful when dealing with Linux environments where command-line tools and Python scripts are commonly used for data analysis tasks.

Setting Up the Environment

Before writing the counting script, ensure you have Python 3 installed on your system. Most modern Linux distributions include Python by default, but you may need to install development headers if you plan to use additional packages later. You do not need any external libraries like pandas or nltk for this basic task, as standard library modules are sufficient and faster for simple counting operations. If you encounter permission errors while trying to install packages globally, refer to our guide on handling Externally managed Environment PIP errors. This often occurs in newer Debian-based systems where package managers restrict global Python installations to prevent conflicts with system tools. Using a virtual environment is recommended for isolated project dependencies, though for this specific script, the standard library alone suffices.

Implementing the Counter Logic

The most efficient way to generate bigrams is to use zip() with iterator shifting. By creating two iterators over the same string—one offset by one character—you can pair every character with its successor. This technique avoids explicit indexing and reduces the number of object creations. Here is the core logic:
from collections import Counter
import csv

def count_bigrams(text):
    # Convert to lowercase and remove non-alphabetic characters if needed
    cleaned_text = ''.join(char.lower() for char in text if char.isalpha())
    
    # Create bigrams using zip
    bigrams = zip(cleaned_text, cleaned_text[1:])
    
    # Join pairs into strings and count them
    bigram_strings = [''.join(pair) for pair in bigrams]
    
    return Counter(bigram_strings)
This function returns a Counter object, which is a dictionary subclass designed for counting hashable objects. It automatically handles the tallying process in C-speed, making it significantly faster than manual dictionary updates. The cleaned_text step ensures that spaces, punctuation, and numbers are ignored, focusing only on alphabetic bigrams. If your corpus includes mixed case, converting to lowercase prevents "Th" and "th" from being counted separately.

Processing Large Files Efficiently

For very large corpora, reading the entire file into memory at once can cause MemoryError exceptions. To avoid this, process the file in chunks or line by line. However, be cautious because bigrams can span across line breaks. A robust solution involves maintaining a buffer of the last character from the previous chunk.
def process_file_large(filepath):
    counter = Counter()
    last_char = None
    
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            # Handle bigram crossing line boundaries
            if last_char is not None:
                counter[last_char + line[0]] += 1
            
            # Process internal bigrams
            cleaned_line = ''.join(c.lower() for c in line if c.isalpha())
            bigrams = zip(cleaned_line, cleaned_line[1:])
            for pair in bigrams:
                counter[''.join(pair)] += 1
                
            # Update buffer for next iteration
            if cleaned_line:
                last_char = cleaned_line[-1]
            else:
                last_char = None
                
    return counter
This generator-like approach keeps memory usage constant regardless of file size. It correctly identifies bigrams that might appear at the end of one line and the beginning of the next, assuming the original text was continuous. Note that if your corpus consists of separate documents rather than a single continuous stream, you may want to reset last_char between documents to avoid cross-document artifacts.

Exporting Results to Spreadsheet

Once the counts are computed, exporting them to a spreadsheet format allows for easy sorting and filtering. The csv module in Python’s standard library makes this straightforward. We sort the results by frequency in descending order to highlight the most significant bigrams.
def export_to_csv(counter, filename):
    # Sort by count descending
    sorted_items = counter.most_common()
    
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['Bigram', 'Count'])
        for bigram, count in sorted_items:
            writer.writerow([bigram, count])
The most_common() method returns a list of tuples sorted by count. Writing this to a CSV file produces a structure that Excel interprets correctly. You can then apply filters, create pivot tables, or generate bar charts directly within the spreadsheet application. This workflow bridges the gap between raw data processing and human-readable insights. For users interested in automating other terminal-based data transformations, you might also find our article on calling ifcconvert from the terminal helpful for understanding how to pipe data between command-line tools and scripts.

Frequently Asked Questions

How do I handle punctuation in the bigram count?

The provided code filters out non-alphabetic characters using isalpha(), effectively ignoring punctuation. If you need to include punctuation as part of the bigrams, remove the filter condition and simply join all characters. Be aware that this will increase the vocabulary size significantly.

Can I count trigrams or n-grams instead?

Yes, you can generalize the zip approach by adding more offsets. For trigrams, use zip(text, text[1:], text[2:]). For arbitrary n-grams, consider using sklearn.feature_extraction.text.CountVectorizer or implementing a sliding window loop, though the zip method remains highly efficient for small n values.

What if my text contains Unicode characters?

The code uses UTF-8 encoding when opening files, which supports Unicode. Ensure your input text is properly decoded. If you encounter encoding errors, verify that your source files are saved in UTF-8 format. The isalpha() method works correctly with Unicode letters in Python 3.

Is this method faster than using Pandas?

For simple counting tasks, collections.Counter is generally faster and uses less memory than Pandas because it avoids the overhead of DataFrame creation and alignment. Pandas is beneficial when you need to perform complex joins, merges, or statistical aggregations alongside the counting process.

How can I visualize the top 10 bigrams?

You can print the top 10 items directly from the Counter object using counter.most_common(10). For visualization, export the CSV and use Excel’s charting tools, or use Python libraries like Matplotlib to plot a horizontal bar chart of the top frequencies.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More