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

穿精又带淫゛_ 提交于 2019-11-29 16:34:48

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.

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

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

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))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!