Reputation: 67
I have some code that randomly generates a word from the .txt file. I want this word to also print it's matching definition but it's not working
This is what I currently have
keywords = {'carrot': 'Green Vegetable.',
'apple': 'Red or Green fruit.',
'orange': 'Orange fruit.'}
print ("Here is your keyword")
import random
with open('keywords.txt') as f:
a = random.choice(list(f))
print (a)
print (keywords[a])
It successfully generates the random keyword but does not show the keyword's definition. This is the error that shows
, line 11, in <module>
print (keywords[a])
KeyError: 'apple\n'
The error, I believe, is suggesting that my keywords.txt file claims that the keyword includes \n but It most certainly does not, I have not typed \n anywhere in my code or my .txt file.
Upvotes: 0
Views: 130
Reputation: 82550
Well this is probably because of whitespace characters, like \n
or just your regular old space. You can remove them by random.choice(list(f)).strip()
.
Upvotes: 3
Reputation: 369334
Lines from file contain new line (\n
) characters.
You should strip them.
>>> 'apple\n'.rstrip()
'apple'
>>> 'apple\n'.rstrip('\r\n') # if you want strip only trailing CR and NL.
'apple'
with open('keywords.txt') as f:
a = random.choice([line.rstrip() for line in f])
print (a)
Upvotes: 0