0

I have been trying to randomize only 10 lines from the text file books.txt. unfortunately, I am unable to extract only 10 rows from the text file and then randomize them without mixing the names of the books with their authors, here is my code:

import random

with open("books.txt", 'r') as file:
    for line in file :
        line = line.split(',')
        bookinfo = (line[1].rstrip("\n") +" by " + line[0])
        print(bookinfo)

a = [line]
random.shuffle(a)
print(a)

Here is an example of randomized output I wish to get: The Princess Diaries by Meg Cabot

The Hunt for Red October by Tom Clancy

The Great Gatsby by F. Scott Fitzgerald

Inkheart by Cornelia Funke

Dinotopia : A Land Apart from Time by James Gurney

Flowers For Algernon by Daniel Keyes

Kiss the Dust by Elizabeth Laird

Nineteen Eighty - Four (1984) by George Orwell

Eragon by Christopher Paolini

The Golden Compass by Philip Pullman

This is the content of the text file books.txt:

Douglas Adams,The Hitchhiker's Guide To The Galaxy
Richard Adams,Watership Down
Mitch Albom,The Five People You Meet in Heaven
Laurie Halse Anderson,Speak
Maya Angelou,I Know Why the Caged Bird Sings
Jay Asher,Thirteen Reasons Why
Isaac Asimov,Foundation Series
Ann Brashares,The Sisterhood of the Travelling Pants
Libba Bray,A Great and Terrible Beauty
Dan Brown,The Da Vinci Code
Meg Cabot,The Princess Diaries
Orson Scott Card,Ender's Game
Tom Clancy,The Hunt for Red October
Suzanne Collins,The Hunger Games
F. Scott Fitzgerald,The Great Gatsby
John Flanagan,Ranger's Apprentice Series
Cornelia Funke,Inkheart
William Gibson,Neuromancer
William Golding,Lord of the Flies
William Goldman,The Princess Bride
James Gurney,Dinotopia: A Land Apart from Time
Will Hobbs,Far North
Alice Hoffman,Practical Magic
Aldous Huxley,Brave New World
Guy Gavriel Kay,The Summer Tree
Daniel Keyes,Flowers For Algernon
Patrice Kindl,Owl in Love
Masashi Kishimoto,Naruto
Tite Kubo,Bleach (graphic novel)
Elizabeth Laird,Kiss the Dust
Harper Lee,To Kill a Mockingbird
C S Lewis,The Lion the Witch and the Wardrobe
Robert Ludlum,The Bourne Series
Yann Martel,Life of Pi
Lurlene McDaniel,Breathless
Stephenie Meyer,Twilight Series
Garth Nix,Sabriel
George Orwell,Nineteen Eighty-Four (1984)
Christopher Paolini,Eragon
Gary Paulsen,Hatchet
Jodi Picoult,My Sister's Keeper
Philip Pullman,The Golden Compass
J.K. Rowling,Harry Potter Series
Louis Sachar,Holes
Shueisha,Shonen Jump Series
Neil Shusterman,The Shadow Club
Jeff Smith,Bone Series
Art Spiegelman,Maus: A Survivor's Tale
Amy Tan,The Joy Luck Club
J R R Tolkien,The Lord of the Rings
J R R Tolkien,The Hobbit
Eric Walters,Shattered
H G Wells,The War Of The Worlds
Patricia C. Wrede,Dealing with Dragons
John Wyndham,The Chrysalids

2 Answers2

1

I modified a Martelli-bot answer from here: How do I read a random line from one file? to return an arbitrary number of lines. This will additionally ensure that there are no duplicates in the returned 10 lines.

import random

def random_lines(afile,num_lines=10): 
    counter = 0 
    lines = [] 
    while counter < num_lines: 
        line = next(afile) 
        for num, aline in enumerate(afile, 2): 
            if random.randrange(num): continue 
            line = aline 
        if line.rstrip('\n') not in lines:
            lines.append(line.rstrip('\n')) 
            counter += 1 
        afile.seek(0) 
    return lines 

Usage:

with open('books.txt','r') as f: 
    print(random_lines(f))

Result:

['William Gibson,Neuromancer',
 'Lurlene McDaniel,Breathless',
 'Amy Tan,The Joy Luck Club',
 'Neil Shusterman,The Shadow Club',
 'H G Wells,The War Of The Worlds',
 'Christopher Paolini,Eragon',
 'J R R Tolkien,The Hobbit',
 "John Flanagan,Ranger's Apprentice Series",
 'Philip Pullman,The Golden Compass',
 'Yann Martel,Life of Pi']
martineau
  • 119,623
  • 25
  • 170
  • 301
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
0

this?

import random

bookinfo_list = []
with open("books.txt", 'r') as file:
    for line in file :
        line = line.split(',')
        bookinfo = (line[1].rstrip("\n") +" by " + line[0])
        bookinfo_list.append(bookinfo)

first_10_bookinfo = bookinfo_list[:10]
other_bookinfo = bookinfo_list[10:]

random.shuffle(first_10_bookinfo)

shuffled_bookinfo_list = first_10_bookinfo + other_bookinfo
print(shuffled_bookinfo_list)