Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

python - Using a text file to lay out a words into a grid form

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...