Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select a random word from a txt file in python version 3.4?

**
I have a txt file called ‘All_Words’ and it consist of 2000 words and i’m making a hangman so i needed to choose a random word i’ve already thought of picking a random number from 0 to 2000 and read the line of the number to chose but i don’t know how to do that, also some background info:

i am in 8th grade and i like coding im trying to get better so i’m trying to get what people suggest and try to figure out what every part does and the reserved words such as ‘global’ for example

also i have also tried to just shuffle the txt file because i already got it to print the first word so if im a able to shuffle the txt file then it would print a different word an i could create an if statement saying if the word chosen was already chooses then it would shuffle it again and pick he first word again, also i got this idea of the shuffle the txt file from my dad but he only did something called ‘dos’ or something like that he said he did it before it was even called coding so i don’t even know if it world word in python, and i’ve asked my coding teacher and he said he dont know how you would do that because he is use to java and javascript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is what i have so far and also i would like it to only pick one word instead of every word in order:**

import random
with open("All_Words.txt") as file:
    for line in file:
        print(line)
        break

>Solution :

Assuming each word is on a new line in file, you can read the text file into a list and use random.choice() to pick a random element in the list. Then you remove the word from the list so you don’t pick it again.

import random

file = open("All_Words.txt", "r")
words = file.read()

listOfWords = words.split("\n")

randWord = random.choice(listOfWords)
print(randWord)

listOfWords.remove(randWord)

newUnqiueRandWord = random.choice(listOfWords)
print(newUnqiueRandWord)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading