Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/General/Other/Count occurrences of a specific word in a file

Count occurrences of a specific word in a file

General/Otherhard2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

Counting word occurrences efficiently depends heavily on file size and the execution environment. For small files, command line tools or simple Python scripts suffice. For large, distributed files, a…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
243
questions in General/Other
Difficulty Split
151E|43M|49H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
KPMG
Key Concepts Tested
pythonspark

Why This Question Matters

This hard-level General/Other question appears frequently in data engineering interviews at companies like KPMG. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (python, spark) will help you answer variations of this question confidently.

How to Approach This

This is a senior-level question that tests architectural thinking. Lead with the high-level design, then drill into specifics. Discuss trade-offs explicitly - there is rarely one correct answer. Show awareness of scale, fault tolerance, and operational complexity. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
329 wordsIncludes code

Counting word occurrences efficiently depends heavily on file size and the execution environment. For small files, command-line tools or simple Python scripts suffice. For large, distributed files, a distributed processing framework like Apache Spark is essential.

Mechanics and Trade-offs

Command Line (Linux/Unix): For single, moderately sized files, grep -o 'word' file.txt | wc -l is effective for counting occurrences. Note that grep -c counts lines* containing the word, not individual occurrences. Use grep -i for case-insensitivity and grep -w for whole word matching. This approach is single-threaded and can be slow or memory-intensive for multi-gigabyte files.
* Python: For larger files that fit into memory, collections.Counter is efficient. For files exceeding available memory, iterate line by line, processing chunks to avoid loading the entire file. This can be combined with regular expressions (re module) for robust case-insensitivity (re.IGNORECASE) and word boundary (\b) handling.

    import re
    from collections import Counter

def count_word_occurrences_python(filepath: str, word: str) -> int:
target_pattern = re.compile(r'\b' + re.escape(word) + r'\b', re.IGNORECASE)
total_count = 0
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
total_count += len(target_pattern.findall(line))
return total_count


* Apache Spark (PySpark): For petabyte-scale data distributed across a cluster, Spark is ideal. It leverages parallel processing across partitions. The workflow involves reading the text file into an RDD or DataFrame, using flatMap to tokenize lines into individual words, filter to select the target word (handling case-insensitivity and word boundaries), and then count() to get the total. Spark handles fault tolerance and distributes computation, potentially involving shuffles for aggregations across worker nodes.

Best Practices

Always consider case-insensitivity (e.g., lower() in Python/Spark, grep -i) and word boundaries (e.g., \b in regex, grep -w) to ensure accurate counts. For large files, prioritize streaming or distributed processing over loading the entire file into memory to prevent OutOfMemory errors.

In the interview, also mention the importance of handling various character encodings (e.g., UTF-8) and the performance implications of complex regular expressions versus simpler string matching.

⚡
Pro Tip

Pro-Move: 'For 10GB file we use Spark—Python loads entire file; Spark streams; 100x faster.' Red Flag: Loading 10GB into memory—use streaming or Spark.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related General/Other Questions

hardHave you worked on Data Warehousing projects?FreemediumHow would you read data from a web API? What steps would you follow after reading the data?FreehardRetrieve the most recent sale_timestamp for each product (Latest Transaction).FreehardWhat is the difference between OLTP and OLAP?FreemediumWhat is the difference between SQL and NoSQL databases?Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked General/Other interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore General/Other questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer