How To Load A Word List Into Python
I'm working through an introductory Python programming course on MIT OCW. On this problem set I've been given some code to work on and a text file. The code and the text file are i
Solution 1:
line = inFile.readline( )
should be readlines()
, plural.
readline
would read only a single line. The reason why only one word is read.
Using readlines()
would give you a list delimited by new line characters in your input file.
Solution 2:
raw file like this:
cat wordlist.txt
aa
bb
cc
dd
ee
python file like this:
import random
defload_words(WORDLIST_FILENAME):
print"Loading word list from file..."
wordlist = list()
# 'with' can automate finish 'open' and 'close' filewithopen(WORDLIST_FILENAME) as f:
# fetch one line each time, include '\n'for line in f:
# strip '\n', then append it to wordlist
wordlist.append(line.rstrip('\n'))
print" ", len(wordlist), "words loaded."print'\n'.join(wordlist)
return wordlist
defchoose_word (wordlist):
return random.choice (wordlist)
wordlist = load_words('wordlist.txt')
then result:
python load_words.py
Loading word list from file...
5 words loaded.
aa
bb
cc
dd
ee
Solution 3:
the function u have written can read words in a single line. It assumes all words are written in single line in text file and hence reads that line and creates a list by splitting it. However, it appears your text file contains some newlines also. Hence u can replace the following with:
line = inFile.readline( )
wordlist = string.split (line)
with:
wordlist =[]
for line in inFile:
line = line.split()
wordlist.extend(line)
print" ", len(wordlist), "words loaded."
Post a Comment for "How To Load A Word List Into Python"