-2

I am using Python 3 and I am very new to this.

import random
words = random.sample(open('letters.txt').readlines(), 9)
print(words)  

I have found solutions but they never seem to work in Python 3.

modusCell
  • 13,151
  • 9
  • 53
  • 80

2 Answers2

2

Use rstrip() to remove the \n newline character:

import random
words = [x.rstrip() for x in random.sample(open('in.txt').readlines(), 9)]

grid = [words[i:i + 3] for i in range(0, len(words), 3)]

[['BLUE', 'ANGRY', 'RED'], ['HAPPY', 'FOO', 'ORANGE'], ['JOYFUL', 'YELLOW', 'SAD']]

If you want to print them out:

import random

with open('in.txt') as f: # with closes your files automatically 
    words = random.sample([x.rstrip() for x in f],9)
    grid = [words[i:i + 3] for i in range(0, len(words), 3)]
    for x,y,z in grid:
        print (x,y,z)



In [5]: with open('in.txt') as f: # with closes your files automatically 
   ...:             words = random.sample([x.rstrip() for x in f],9)
   ...:             grid = [words[i:i + 3] for i in range(0, len(words), 3)]
   ...:             for x,y,z in grid:
   ...:                     print (x,y,z)
   ...:         
BLUE GREEN SAD
RED JOYFUL FOO
ORANGE HAPPY YELLOW
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • @NatalieThompson, do you just want to print the data? – Padraic Cunningham Aug 24 '14 at 09:15
  • you need to put it in a `while` loop, use `time.clock` or `time.sleep` depending on what you want to do to keep track of the seconds past, you will just need to call `words = random.sample([x.rstrip() for x in f],9)` every 30 seconds inside your loop and display that. – Padraic Cunningham Aug 24 '14 at 09:56
0

After making a little search in stackoverflow I found this Print new output on same line

So perhaps could do something like (this code is not tested):

import random
// We store all the words to keep reference to the one is not displayed
dictionary = open('words.txt').readlines() 

words = random.sample(dictionary, 9)
for index in range(9)
  ending = ' '
  if index+1 % 3 == 0
    ending = '\n'
  print(words[i], end=ending)
Community
  • 1
  • 1
lsamayoa
  • 144
  • 4