简体   繁体   中英

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.

My thoughts were as follows:

1) Read the text file using readlist = open('N:\\Words.txt', 'r')

2) Python turns this into a list Python randomly chooses 9 using import random

3) Python diplays the list in a 3x3 grid

I have tried various things - readline, readlines, append characters - but with no or limited success. 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:

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:

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.

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. string method splitlines() splits the string on newlines returning an array of strings with the newline stripped off.

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). words is still in scope after the block is finished. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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