1

I'm trying to get the output of my program all on one line and when i print "end=''" it doesn't seem to be working. Any ideas?

Here is my code:

import random

thesaurus = {}
with open('thesaurus.txt') as input_file:
    for line in input_file:
        synonyms = line.split(',')
        thesaurus[synonyms[0]] = synonyms[1:]

print ("Total words in thesaurus: ", len(thesaurus))

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)


newlist = []
for x in part2:
    s = random.choice(thesaurus[x]) if x in thesaurus else x
    s = random.choice(thesaurus[x]).upper() if x in thesaurus else x
    newlist.append(s)

newphrase = ' '.join(newlist)

print(newphrase, end=' ')

Right now, for some reason, my program is printing out :

i LOVE FREEDOM
 SUFFICIENCY apples

with the input "i like to eat apples"

and the expected output is:

 i LOVE FREEDOM SUFFICIENCY apples

Any help is appreciated!!

1 Answer 1

1

Its not a problem with end='' at all. Lines read from the file still have the newline. When you split the line, the final entry will have a newline as with this example:

>>> 'foo,bar,baz\n'.split(',')
['foo', 'bar', 'baz\n']

Your problem is that you substituted "FREEDOM\n" not just "FREEDOM". Just strip the line before use:

thesaurus = {}
with open('thesaurus.txt') as input_file:
    for line in input_file:
        synonyms = line.strip().split(',')
        thesaurus[synonyms[0]] = synonyms[1:]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.