简体   繁体   English

将列表从文本文件转换为python列表

[英]Turning list from text file into python list

I am teaching a class and I want them to read a list of 10 words from a text file and then randomly display 9 of them in a 3 by 3 grid. 我正在授课,我希望他们从文本文件中读取10个单词的列表,然后在3 x 3的网格中随机显示9个单词。

My thoughts were as follows: 我的想法如下:

1) Read the text file using readlist = open('N:\\Words.txt', 'r') 1)使用readlist = open('N:\\ Words.txt','r')读取文本文件

2) Python turns this into a list Python randomly chooses 9 using import random 2)Python将其转换为列表Python使用import random随机选择9

3) Python diplays the list in a 3x3 grid 3)Python在3x3网格中显示列表

I have tried various things - readline, readlines, append characters - but with no or limited success. 我尝试了多种方法-readline,readlines,追加字符-但没有成功或成功有限。 I am missing something obvious but can't see it. 我缺少明显的东西,但看不到。

This adds the first word to the list, but how do I add the second word: 这会将第一个单词添加到列表中,但是如何添加第二个单词:

readlist = open('N:\Words.txt', 'r')
listwords=[]
firstword=readlist.read(5)
listwords.append(firstword)
print (listwords)

Use random.sample to get nine random words and split the list returned into three sublists: 使用random.sample获取九个随机词,并将返回的列表分为三个子列表:

from random import sample
from pprint import pprint as pp

with open("text.txt") as f:
    samp = sample(f.read().split(), 9)
    pp([samp[i:i+3] for i in range(0, len(samp), 3)],width=40)

 [['seven', 'ten', 'four'],
 ['one', 'five', 'nine'],
 ['eight', 'two', 'six']]

text.txt: 的text.txt:

one
two
three
four
five
six
seven
eight
nine
ten

This will work if you have a word per line or a single line where the words are separated by whitespace. 如果您每行有一个单词,或者一行由空格分隔的一行,则可以使用此功能。

open creates a file object. open创建一个文件对象。

Try this: 尝试这个:

with open(filename) as f:
    words = f.read().splitlines()

This is assuming the file has one word per line. 假设文件每行只有一个单词。 f.read() returns the whole file as a string. f.read()以字符串形式返回整个文件。 string method splitlines() splits the string on newlines returning an array of strings with the newline stripped off. 字符串方法splitlines()在换行符上分割字符串,返回去除了换行符的字符串数组。

I'm using a block here with open(filename) as f: so that the file will close immediately after you're reading with from it (once the block finishes). 我在这里使用一个with open(filename) as f:的块with open(filename) as f:这样,当您从中读取文件后,文件将立即关闭(一旦块完成)。 words is still in scope after the block is finished. 块完成后, words仍在范围内。 This style just reads nicely and prevents the need to manually close the file. 这种样式读起来很不错,无需手动关闭文件。

from random import shuffle

words = open('words.txt').read().splitlines()
shuffle(words)

chunks=[words[x:x+3] for x in xrange(0, 9, 3)]
for chunk in chunks:
    print chunk

['d', 'f', 'a']
['i', 'j', 'g']
['e', 'h', 'b']

words.txt contains all letters from a to j in a separate line each. words.txt包含从a到j的所有字母,每个字母都在单独的行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM