0

I have a txt file and a dictionary, where keys are adjectives, values are their synonyms. I need to replace the common adjectives from the dictionary which I meet in a given txt file with their synonyms - randomly! and save both versions - with changed and unchanged adjectives - line by line - in a new file(task3_edited_text). My code:

#get an English text as a additional input
filename_eng = sys.argv[2]
infile_eng = open(filename_eng, "r")
task3_edited_text = open("task3_edited_text.txt", "w")

#necessary for random choice
import random 

#look for adjectives in English text
#line by line
for line in infile_eng:
    task3_edited_text.write(line)
    line_list = line.split()
    #for each word in line
    for word in line_list:
        #if we find common adjectives, change them into synonym, randomly
        if word in dict.keys(dictionary):
            word.replace(word, str(random.choice(list(dictionary.values()))))
        else:
            pass
    task3_edited_text.write(line)

Problem is in the output adjectives are not substituted by their values.

Luiza
  • 1
  • 1

1 Answers1

0
line_list = line.split()
...
task3_edited_text.write(line)

The issue is that you try to modify line_list, which you created from line. However, line_list is simply a list made from copying values generated from line ; modifying it doesn't change line in the slightest. So writing line to the file writes the unmodified line to the file, and doesn't take your changes into account.

You probably want to generate a line_to_write from line_list, and writing it to the file instead, like so:

line_to_write = " ".join(line_list)
task3_edited_text.write(line_to_write)

Also, line_list isn't even modified in your code as word is a copy of an element in line_list and not a reference to the original. Moreover, replace returns a copy of a string and doesn't modify the string you call it on. You probably want to modify line_list via the index of the elements like so:

for idx, word in enumerate(line_list):
    #if we find common adjectives, change them into synonym, randomly
    if word in dict.keys(dictionary):
        line_list[idx] = word.replace(word, str(random.choice(list(dictionary.values()))))
    else:
        pass
OctaveL
  • 1,017
  • 8
  • 18