Skip to content

Commit d4df67c

Browse files
The Python script with the associated text file.
“word_list.py” and “word_list.txt” have been added.
1 parent 1c8eee0 commit d4df67c

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

word_list.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import os
2+
3+
def remove_duplicates_and_sort(filepath):
4+
# Check if the file exists
5+
if not os.path.exists(filepath):
6+
# Create a new file if it does not exist
7+
with open(filepath, 'w', encoding='utf-8') as file:
8+
pass
9+
print(f"The file '{filepath}' was created because it was not found.")
10+
return 0, 0
11+
12+
# Read the words from the file
13+
with open(filepath, 'r', encoding='utf-8') as file:
14+
words = file.readlines()
15+
16+
# Remove whitespace and newlines
17+
words = [word.strip() for word in words]
18+
19+
# Count the number of duplicates
20+
count_before = len(words)
21+
words = sorted(set(words))
22+
duplicate_count = count_before - len(words)
23+
24+
# Write the sorted words back to the file
25+
with open(filepath, 'w', encoding='utf-8') as file:
26+
for word in words:
27+
file.write(word + '\n')
28+
29+
return duplicate_count, len(words)
30+
31+
def add_word(filepath, new_word):
32+
# Read the current words from the file
33+
with open(filepath, 'r', encoding='utf-8') as file:
34+
words = file.readlines()
35+
36+
# Remove whitespace and newlines
37+
words = [word.strip() for word in words]
38+
39+
# Check if the new word already exists
40+
if new_word in words:
41+
print(f"The word '{new_word}' is already in the word list and cannot be added.")
42+
return
43+
44+
# Add the new word to the list
45+
words.append(new_word)
46+
47+
# Sort the list alphabetically
48+
words = sorted(words)
49+
50+
# Write the updated list back to the file
51+
with open(filepath, 'w', encoding='utf-8') as file:
52+
for word in words:
53+
file.write(word + '\n')
54+
55+
def main():
56+
filepath = 'word_list.txt'
57+
58+
# Remove duplicate words and sort at the start
59+
duplicate_count, word_count = remove_duplicates_and_sort(filepath)
60+
print(f"Number of duplicates found: {duplicate_count}")
61+
print(f"Number of words after sorting and removing duplicates: {word_count}")
62+
63+
# User can add new words
64+
while True:
65+
new_word = input("Enter a new word (or 'x' to quit): ")
66+
if new_word.lower() == 'x':
67+
break
68+
add_word(filepath, new_word)
69+
70+
if __name__ == "__main__":
71+
main()
72+

word_list.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
apple
2+
five
3+
four
4+
house
5+
one
6+
stone
7+
three
8+
tree
9+
two

0 commit comments

Comments
 (0)