1

I want to randomly retrieve and print a whole line from a text file.

The text file is basically a list and so each item on that list needs to be searched.

import random

a= random.random

prefix = ["CYBER-", "up-", "down-", "joy-"]

suprafix = ["with", "in", "by", "who", "thus", "what"]

suffix = ["boy", "girl", "bread", "hippy", "box", "christ"]

print (random.choice(prefix), random.choice(suprafix), random.choice(prefix), random.choice(suffix))

this is my code for if i were to just manually input it into a list but i can't seem to find how to use an array or index to capture line by line the text and use that

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • What exactly do you want to do? Do you want to randomly choose one of those three lists? Do you want to choose a random element from each list? – KSFT Mar 18 '15 at 21:38
  • what do you mean by `The text file is basically a list ` – hyades Mar 18 '15 at 21:39

3 Answers3

0

Use Python's file.readLines() method:

with open("file_name.txt") as f:
    prefix = f.readlines()

Now you should be able to iterate through the list prefix.

logic
  • 1,739
  • 3
  • 16
  • 22
0

I'm not sure I completely understand what you're asking, but I'll try to help.

  • If you're trying to choose a random line from a file, you can use open(), then readlines(), then random.choice():

    import random
    line = random.choice(open("file").readlines())
    
  • If you're trying to choose a random element from each of three lists, you can use random.choice():

    import random
    choices=[random.choice(i) for i in lists]
    

    lists is a list of lists to choose from here.

KSFT
  • 1,774
  • 11
  • 17
0

Those answers have helped me grab things from a list in a text file. as you can see in my code below. But I have three lists as text files and I am trying to generate a 4 word message randomly, choosing from the 'prefix' and 'suprafix' list for the first 3 words and 'suffix' file for the fourth word but I want to prevent it, when printing them, from picking a word that was already chosen by the random.choice function

import random

a= random.random

prefix = open('prefix.txt','r').readlines()

suprafix = open('suprafix.txt','r').readlines()

suffix = open('suffix.txt','r').readlines()

print (random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(prefix + suprafix), random.choice(suffix))

as you can see it chooses randomly from those 2 lists for 3 words