Using a text file to lay out a words into a grid f

2019-01-28 22:31发布

问题:

I have a list of 6 words from a text file and would like to open the file to read the list of words as a 3x2 grid, also being able to randomise the order of the words every time the program is run.

words are:

cat, dog, hamster, frog, snail, snake

i want them to display as: (but every time the program is run to do this in a random order)

cat    dog     hamster
frog   snail   snake 

so far all i've managed to do is get a single word from the list of 6 words to appear in a random order using - help would be much appriciated

import random

words_file = random.choice(open('words.txt', 'r').readlines())
print words_file

回答1:

Here's another one:

>>> import random
>>> with open("words.txt") as f:
...    words = random.sample([x.strip() for x in f], 6)
... 
...
>>> grouped = [words[i:i+3] for i in range(0, len(words), 3)]
>>> for l in grouped:
...     print "".join("{:<10}".format(x) for x in l)
...     
... 
snake     cat       dog       
snail     frog      hamster   

First we read the contents of the file and pick six random lines (make sure your lines only contain a single word). Then we group the words into lists of threes and print them using string formatting. The <10 in the format brackets left-aligns the text and pads each item with 10 spaces.



回答2:

For selecting the 6 words, you should try random.sample:

words = randoms.sample(open('words.txt').readlines(), 6)


回答3:

You'll want to look into string formatting!

import random

with open('words.txt','r') as infile:
    words_file = infile.readlines()

random.shuffle(words_file) # mix up the words

maxlen = len(max(words_file, key=lambda x: len(x)))+1
print_format = "{}{}{}".format("{:",maxlen,"}")

print(*(print_format.format(word) for word in words_file[:3])
print(*(print_format.format(word) for word in words_file[3:])

There are better ways to run through your list grouping by threes, but this works for your limited test case. Here's a link to some more information on chunking lists

My favorite recipe is chunking with zip and iter:

def get_chunks(iterable,chunksize):
    return zip(*[iter(iterable)]*chunksize)

for chunk in get_chunks(words_file):
    print(*(print_format.format(word) for word in chunk))