使用文本文件将单词排成网格形式

2 投票
3 回答
2114 浏览
提问于 2025-04-18 02:25

我有一个包含6个单词的列表,这些单词来自一个文本文件。我想打开这个文件,读取这些单词,并把它们以3行2列的方式显示出来。而且每次运行程序时,单词的顺序都要随机变化。

这些单词是:

cat, dog, hamster, frog, snail, snake

我希望它们显示成这样:(不过每次运行程序时,顺序都要随机)

cat    dog     hamster
frog   snail   snake 

到目前为止,我只成功让这6个单词中的一个以随机顺序出现,能得到一些帮助我会非常感激。

import random

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

3 个回答

1

要选择6个单词,你可以试试 random.sample 这个方法:

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

你可以看看 字符串格式化

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:])

虽然有更好的方法可以把你的列表每三项分成一组,但这个方法在你有限的测试情况下是可以用的。这里有个链接,提供了更多关于如何分块列表的信息

我最喜欢的做法是用 zipiter 来分块:

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))
2

这是另一个例子:

>>> 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   

首先,我们读取文件的内容,然后随机挑选六行(确保每行只包含一个单词)。接着,我们把这些单词分成三组一组,并用字符串格式化的方式打印出来。格式中的 <10 是用来让文本左对齐,并且每个项目前面留出10个空格。

撰写回答