jeudi 27 avril 2017

Replacing words with dictionary python

I am trying to replace the words in the lyrics file with the ones in the dictionary. However, when i try to execute this, I get a bunch of errors that I don't quite understand. I am trying to first split the words in the text file into a variable and iterate through that so if there is a matching word in the dictionary, it will replace it. If I delete the lyrics sections and just try it with a user input, it works just fine. I also want to keep the format the way it is originally. If anyone has an idea on how to fix this, that would be great. Thanks

import random

file = open("python_asg10_Roget_Thesaurus.txt", "r")
data = file.read()

data_split = data.split("\n")

thesaurus = {}


for line in data_split:
    words = line.split(',')
    thesaurus[words[0]] = words[1:]

lyric_file = open("paris.txt", "r")
lyric_data = lyric_file.read()
lyric_split = lyric_data.split("\n")

lyric = ""

for i in lyric_split:
    word = i.split(' ')
    lyric += str(word)

new_phrase = ""

for char in lyric:
    if char.isalnum() or char.isspace():
        new_phrase += char

phrase_list = new_phrase.split(' ')

final_phrase = ""

for word in phrase_list:
    low = word.lower()
    if low in thesaurus:
        rand_choice = random.choice(thesaurus[low])
        final_phrase += rand_choice.upper() + " "
    else:
        final_phrase += word + " "

print(new_phrase)




Aucun commentaire:

Enregistrer un commentaire