Trying to Make Some Working Python Code Refer to a Dictionary File

This code replaces the words on the left side with the words on the right side. However, I want the two columns of words in a separate file that I’ll name “inputDictionary.txt”.

So here’s the code (and I’ll admit that I went back and forth with ChatGPT to get it to work, and the comments are all by the robot; also, sorry about the harsh words in my list):

import re

# Function to replace words in the text
def replace_words(text):
    # Dictionary containing the word replacements
    replacements = {
        'genocidal': 'genocídal',   # Replace 'genocidal' with 'genocídal'
        'maniacs': 'maníacs',       # Replace 'maniacs' with 'maníacs'
        'murderers': 'murḑereṙs'     # Replace 'murderers' with 'murḑereṙs'
    # Create a regular expression pattern to match the words
    # The pattern uses word boundaries (\b) to ensure whole word matching
    # The pattern is constructed by joining the escaped keys of the replacements dictionary
    pattern = r'\b(' + '|'.join(re.escape(word) for word in replacements.keys()) + r')\b'
    # Use re.sub() to replace the matched words with their replacements
    # The lambda function retrieves the matched word and returns the replacement from the dictionary
    replaced_text = re.sub(pattern, lambda match: replacements[], text)
    # Return the modified text
    return replaced_text

input_file = "Input.txt"      # File path of the input file
output_file = "output.txt"    # File path of the output file

# Open the input file for reading and the output file for writing
# Both files are encoded in UTF-8
with open(input_file, 'r', encoding='utf-8') as f_input, open(output_file, 'w', encoding='utf-8') as f_output:
    # Iterate over each line in the input file
    for line in f_input:
        # Remove leading/trailing whitespaces from the line
        # Replace words using the replace_words() function
        replaced_line = replace_words(line.strip())
        # Write the modified line to the output file, followed by a newline character
        f_output.write(replaced_line + "\n")

define an empty dictionary.
read the inputdictionary file.
for each line in the inputdictionary,
split the line
add the item to the dictionary.

change the replace_words function to use the dictionary you created.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.