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/Spark/Big Data/Write a Python script to find the count of each word in a text file using Spark.

Write a Python script to find the count of each word in a text file using Spark.

Spark/Big Datamedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To count word occurrences in a text file using Spark, the standard approach leverages the PySpark DataFrame API to read the file, tokenize lines into words, and then aggregate these words. This method…

🤖 Analyze Your Answer
Frequency
Low
Asked at 2 companies
Category
452
questions in Spark/Big Data
Difficulty Split
88E|81M|283H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
AltimetrikInfosys
Key Concepts Tested
partitionpythonsparksql

Why This Question Matters

This medium-level Spark/Big Data question appears frequently in data engineering interviews at companies like Altimetrik, Infosys. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, python, spark) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
374 wordsIncludes code

To count word occurrences in a text file using Spark, the standard approach leverages the PySpark DataFrame API to read the file, tokenize lines into words, and then aggregate these words. This method is efficient and scalable for large datasets.

Mechanics and Why it Works

The process begins by reading the text file, where each line becomes a single row in a DataFrame. The F.split(F.col("value"), "\\s+") function then transforms each line into an array of words, using whitespace as a delimiter. Crucially, F.explode() flattens this array, creating a new row for each word, which is essential for subsequent aggregation. Finally, groupBy("word").count() groups all identical words together and counts their occurrences. This sequence of transformations is optimized by Spark's Catalyst optimizer, which builds an efficient execution plan (DAG) to distribute the work across the cluster.

PySpark Implementation and Performance Considerations

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

# Initialize Spark Session
spark = SparkSession.builder.appName("WordCount").getOrCreate()

# Read the text file into a DataFrame
df = spark.read.text("path/to/file.txt")

# Split lines into words, explode the array, and count
word_counts = df.select(F.explode(F.split(F.col("value"), "\\s+")).alias("word")) \
.groupBy("word") \
.count()

# Show results (or write to storage)
word_counts.show()

# Stop Spark Session
spark.stop()

For large files, Spark partitions are critical for parallelism; spark.read.text typically creates partitions based on HDFS block sizes. The groupBy operation is a wide transformation that triggers a shuffle, moving data across the network to group identical keys. This is the most expensive part of the operation. To mitigate performance issues:

* Data Skew: If certain words (e.g., "the", "a") are extremely common, they can lead to data skew, causing a few tasks to process disproportionately more data and become bottlenecks. Repartitioning by key or using salting techniques can help.
* Shuffle Optimization: While the DataFrame API often optimizes shuffles, understanding the underlying reduceByKey semantics (available in RDDs) reveals how partial aggregation (combiner pattern) can reduce the amount of data shuffled. Spark's optimizer often applies similar techniques implicitly.
* Resource Tuning: Adjust spark.sql.shuffle.partitions and executor memory settings to match cluster resources and data volume.

In the interview, also mention the importance of monitoring Spark UI to identify shuffle bottlenecks and data skew, and how this fundamental problem illustrates core distributed computing concepts.

⚡
Pro Tip

Red Flag: Using split(" ") and forgetting empty strings or multiple spaces. Pro-Move: 'I use regex split for whitespace, filter out empty strings, and repartition before groupBy when word distribution is skewed.'

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

Related Spark/Big Data Questions

mediumWhat is the difference between repartition and coalesce in Apache Spark?FreehardWhat is the difference between SparkSession and SparkContext in Spark?FreemediumWhat is the difference between cache() and persist() in Spark? When would you use each?FreemediumWhat is the difference between groupByKey and reduceByKey in Spark?FreemediumWhat is the difference between narrow and wide transformations in Apache Spark? Explain with examples.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 Spark/Big Data interview questions, reported at 2 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Spark/Big Data 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