|
| 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 | + |
0 commit comments