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

Answer

Read, split, deduplicate, and sort

Save the official four-line input as romeo.txt. Run this Python 3 program from the directory containing the file and enter romeo.txt when prompted:

filename = input("Enter file: ")
words = []

with open(filename, encoding="utf-8") as handle:
    for line in handle:
        for word in line.split():
            if word not in words:
                words.append(word)

words.sort()
print(words)

line.split() separates the words at whitespace. The membership test prevents duplicate entries; append() adds each new word, and sort() puts the final list in Python's ascending string order. The program follows the exercise's required list-based method rather than substituting a set.

Complete output for the official input

Enter file: romeo.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

There are 26 distinct words. Case is preserved: the program does not call lower() or remove punctuation. For this ASCII input, Python places the capitalized words before the lowercase words. The output above was checked by running the program with the official file, not inferred from a longer version of Shakespeare's text.

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.

Sources

Эти источники подтверждают изложенные выше концепции и методы.