So I have most of the code down an accurate. The goal is to take phrases from a song and replace the words with synonyms from a thesaurus file. However, only a user designated % of the time(so not all words will be changed)
import random
newfile = open("/Users/fp790/Desktop/assignment 10/python-asg10-Roget-Thesaurus.txt","r")
justinfile = open("/Users/fp790/Desktop/bieber_baby.txt","r")
splitjustin = justinfile.read().split("\n")
newjustin = []
thesaurus = {}
splitdata = newfile.read().split("\n")
for x in range (len(splitdata)):
line = splitdata[x].split(",")
word = line[0]
thesaurus[word] = line[1:]
print("Total words in thesaurus:",len(thesaurus))
chance = int(input("Enter a % chance to change a word: "))
for q in splitjustin:
rannum = random.randint(1,10)
r = q.split()
for s in r:
if s in thesaurus:
if rannum <= chance /100:
ran = len(thesaurus[s])
ranlis = random.randint(0,ran - 1)
t = q.replace(s,str.upper(thesaurus[s][ranlis]),1)
newjustin += [t]
else:
newjustin += [q]
the thesaurus code is fine. However even when I set chance to 100 only a couple words are changed. I think my loop/random number logic might be off. How do I get it to execute only x% of the time?
Aucun commentaire:
Enregistrer un commentaire