【问题标题】:Randomise only 10 rows from the text file从文本文件中仅随机化 10 行
【发布时间】:2020-05-22 23:36:50
【问题描述】:

我一直试图从文本文件 books.txt 中仅随机化 10 行。不幸的是,我无法从文本文件中仅提取 10 行,然后在不将书名与其作者混合的情况下将它们随机化,这是我的代码:

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)

这是我希望获得的随机输出示例: 梅格·卡博特的公主日记

汤姆克兰西的《寻找红色十月》

F. Scott Fitzgerald 的《了不起的盖茨比》

Cornelia Funke 的墨水心

Dinotopia : A Land with Time by James Gurney

丹尼尔·凯斯《献给阿尔杰农的鲜花》

伊丽莎白·莱尔德亲吻尘埃

乔治·奥威尔的十九岁八十四 (1984)

克里斯托弗·保利尼的《Eragon》

菲利普·普尔曼的黄金罗盘

这是文本文件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

【问题讨论】:

    标签: python python-3.x list random


    【解决方案1】:

    我从这里修改了一个 Martelli-bot 答案:How do I read a random line from one file? 以返回任意数量的行。这将额外确保返回的 10 行中没有重复。

    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 
    

    用法:

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

    结果:

    ['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']
    

    【讨论】:

      【解决方案2】:

      这个?

      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) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-27
        • 2015-11-26
        • 2015-01-06
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        • 1970-01-01
        相关资源
        最近更新 更多