Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python’s random module to pick a random word.
There are various ways to perform this operation:
This is the text file we will read from:
Method 1: Using random.choice()
- Using with function, open the file in read mode. The with function takes care of closing the file automatically.
- Read all the text from the file and store in a string
- Split the string into words separated by space.
- Use random.choice() to pick a word or string.
Note: The split() function, by default, splits by white space. If you want any other delimiter like newline character you can specify that as an argument.
The above can be achieved with just a single line of code like this :
Method 2: Using random.randint()
- Open the file in read mode using with function
- Store all data from the file in a string and split the string into words.
- Count the total number of words.
- Use random.randint() to generate a random number between 0 and the word_count.
- Print the word at that position.
My Personal Notes arrow_drop_up
Please Login to comment...