How to extract random words from .txt file using python?

python read random line from large file
write a python program to read a random line from a file
python random word from list
random.choice python
random number file reader - python
how to read a specific line from a text file in python
python random number
how to randomly select a variable in python

I have a .txt file that looks like this:

Title       | Author

-------------------------
title1      | author1

title2      | author2


...        ...

titleN      | authorN

I want to extract 100 random titles from this file, like this:

title1

title2

...

title100

I tried this:

import random
with open('file.txt','r') as f:
  title = f.read().split('|')

for i in range (0,100):
 print(random.choice(title))

But during the execution, the program prints also random authors name. How can I avoid this?

When you do this:

with open(path,'r') as f:
    title = f.read().split('|')

f.read() gives you the whole files as a string. Splitting that on | gives a list with both authors and titles (and new lines and spaces).

Instead, you can process the lines and split as you go. With something like:

with open(path) as f:
    titles = [l.split('|')[0].strip() for l in f]

This will give you a clean list of titles like:

['title1', 'title2', 'title3', 'title4', 'title5']

With that you can use random.sample() to get however many random items you want.

import random

path = "path/to/file.txt"
n = 100

with open(path) as f:
    titles = [l.split('|')[0].strip() for l in f]

random.sample(titles, n)

This assumes you don't want duplicates.

Python File I/O: Read a random line from a file, import random def goal_word(min_length=7, filename="words.txt"): You don't need to read the whole file in at once nor use random.choice() if you use the The algorithm is based on the idea that you select later samples� with open ('lorem.txt', 'rt') as myfile: # Open lorem.txt for reading text contents = myfile.read () # Read the entire file to a string print (contents) # Print the string. Note. Indentation is important in Python. Python programs use white space at the beginning of a line to define scope, such as a block of code.

You can use .readlines() instead of .read() to read the file line by line to a list. Then you can use .split('|')[0].strip() after when you've selected a random row, to only show the title part of it:

import random

with open('file.txt', 'r') as f:
    title = f.readlines()

for i in range(0, 100):
    choice = random.choice(title)
    print(choice.split('|')[0].strip())

Alternatively you can process the file immediately after you've read it:

import random

with open('file.txt', 'r') as f:
    title = [line.split('|')[0].strip() for line in f.readlines()]

for i in range(0, 100):
    print(random.choice(title))

Here's a demonstration how the .split('|')[0].strip() works:

>>> choice = "title1      | author1"
>>> choice.split('|')
['title1      ', ' author1']
>>> choice.split('|')[0]
'title1      '
>>> choice.split('|')[0].strip()
'title1'

Pick a random big word from a list of words using Python, random number file reader - python python read file line by line. I have a text file that has six words on one line, I need to randomly generate a word from that line � In this article, I am going to let you know how to extract text from a PDF file in Python. Before diving into the topic, a lot of things need to be configured. The pdftotext module is used as the main component to extract text.

Have a look at title after you read it in. If my text file is

title1 | author1
title2 | author2

title will be ['title1 ', ' author1\ntitle2 ', ' author2\n']. Randomly choosing from this list will sometimes give you titles, sometimes authors, and sometimes both.

A better approach would something like the following:

import random

# read in the file and split lines
with open("file.txt", "r") as f:
    lines = f.read().splitlines()
# lines = ["title1 | author1", "title2 | author2"]

titles = [line.split("|")[0].strip() for line in lines]
# titles = ["title1", "title2"]

Note that we need to call strip to strip any extra whitespace off the ends of the title.

You can now proceed with your sampling, but I suspect that you want 100 unique titles and not just 100 random titles. What you are doing is called sampling with replacement, and getting unique titles would be sampling without replacement. You can accomplish this with random.sample as follows (see the random docs):

print(*(random.sample(titles, 100)), sep = "\n")

or equivalently with more familiar syntax

for samp_title in random.sample(titles, 100):
    print(samp_title)

Pulling a random word/string from a line in a text file in python, Secondly, do not use file as one of your variable names. As you can see above, file is highlighted in purple meaning that it is a reserved word in Python. Third, as � Python has a module that is the random module by using the random module to get a random line from the text file(.txt). The following are constraints to get a random line: The file path must be specified to open the file on the computer. We must specify the mode of the file while the file is opening. Importing Random Module:

help! generate random word function from fiveLetter.txt file, If it is relatively small - read the whole file in (using readlines(), and then use random.choice() [code]import By using the random library, you can extract a line out of a text file. How do you convert numbers to words in Python 3, specifically? Python | Extract words from given string We sometimes come through the situations where we require to get all the works present in the string, this can be a tedious task done using naive method. Hence having shorthands to perform this task is always useful.

How to randomly choose a line from a TXT file in Python 3, Python can open, read and write into memory VERY big number of lines in just a moment. So if you don't have like a 1 GB file of words, just load it all and then� How to read a specific line from a text file in Python; How to count the number of lines in a text file in Python . Add some texts to a text file in Python. To add texts to a text file we can use write() function. Here is an easy example on How to add text to a text file in Python.

reading a random line from a text file : learnpython, It's pretty easy. Please, follow the comment in below code: Hide Expand Copy Code. Option Explicit Sub Test() 'display message with random� Assume that we have a text file with the file name this_is_file.txt. Here is the content of the text file: I am line no 1 I am line no 2 I am line no 3 I am line no 4 I am line no 5 I am line no 6 I am line no 7 I am line no 8 I am line no 9 I am line no 10. Now we have to read the texts from line no 5. Then we will use the below code: file

Comments
  • Do you want the possibility of duplicates?
  • Thank you for the answer, this helped a lot!
  • Thank you for your answer!
  • Sure thing. Make sure to mark one of the answers as the definitive answer if you're satisfied. I think all three of us basically said the same thing, so your choice ;)