-2

I am new to python and programming in general and I was trying to make a hangman game. I downloaded a dictionary text file and opened it in pycharm and I applied the random.choice() function on it and it only printed a letter of a random word in the .txt file:

import random

f = open ("/home/ar/Downloads/sowpods.txt")

sowpods = f.read()

sowpods = random.choice(sowpods)

print(sowpods)
Aaron
  • 10,133
  • 1
  • 24
  • 40
Haris
  • 47
  • 4
  • 1
    you don't have a list of words. `f.read()` returns a single string with the entire contents of the file, and a random choice out of a single string is a single character. You can use [`split`](https://docs.python.org/3/library/stdtypes.html#str.split) to split it up into a list. – Aaron Aug 03 '20 at 12:50
  • `sowpods = random.choice(sowpods.split())` Splitting the words by whitespace gives you a random word from the file – Raghul Raj Aug 03 '20 at 12:51

1 Answers1

0

You first need to convert from a list of characters to a list of words. You can do this using string.split().

import random

f = open ("/home/ar/Downloads/sowpods.txt")

sowpods = f.read().split()

sowpods = random.choice(sowpods)

print(sowpods)
Kexus
  • 659
  • 2
  • 6
  • 13