Computer SciencePython Programming

.split Python: Find the Unique Words in romeo.txt

Read the complete official romeo.txt file line by line, split each line into words, remove duplicates with a list, and print the case-preserving sorted result.

Question

PY4E Chapter 8, Exercise 4: Find all unique words in a file (standardized wording).

Using the official romeo.txt file containing a short Shakespeare excerpt, write a Python program that asks for the filename and reads the file one line at a time. Tokenize each line with split(). Maintain a list of distinct words: test each token for membership and append it only when it is absent. After reading all lines, sort the list alphabetically and print it.

Complete input file (romeo.txt):

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

This question has been answered.

Explore the full answer and supporting references to better understand this question.

Verla BasicBest value
$19.99/month
  • Everything in Study Pass
  • Assignments with writing output
  • AI detection and humanizer
  • Basic quotas across every tool
Study Pass
$0.99/month
  • Entire question library
  • Knowledge guides and sources
  • Detailed answers and explanations
  • No AI tools or quotas

Evidence boundary

This answer uses the current PY4E Chapter 8 Exercise 4 and its official four-line romeo.txt. The standardized prompt preserves all programming requirements. The shown result applies to that exact input; a different file, case normalization, or punctuation cleanup can change it. Python string order is used without a locale-specific collation rule.