使用文本文件将单词排列成网格形式 [英] Using a text file to lay out a words into a grid form

查看:127
本文介绍了使用文本文件将单词排列成网格形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自文本文件的6个单词列表,并且希望打开文件以3x2格子的形式阅读单词列表,并且每次程序运行时也能够随机排列单词的顺序。 / p>

字样:

 狗,仓鼠,青蛙,蜗牛,蛇

我希望它们显示为:(但每次

 猫狗仓鼠
青蛙蜗牛蛇

到目前为止,我设法做的是从6个单词列表中获取一个单词,以随机顺序出现使用 - 帮助将大大appriciated

 进口随机

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


解决方案

这是另一个:

 >>> import random 
>>>打开(words.txt)为f:
... words = random.sample([x]中的x [x]),6)
...
...
>>> groupped = [words [i:i + 3] for i in range(0,len(words),3)]
>>>对于分组中的l:
... print.join({:<10}。格式(x)for x in l)
...
...
蛇猫狗
蜗牛青蛙仓鼠

首先我们阅读文件并挑选六个随机行(确保你的行只包含一个单词)。然后我们将这些单词分组成三个列表,并使用字符串格式打印它们。格式括号中的< 10 左对齐文本并用10个空格填充每个项目。


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

解决方案

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.

这篇关于使用文本文件将单词排列成网格形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆