To print one random word per line, your loop could be:
for line in wordsf:
word = random.choice(line.split())
print(word)
If there are lines with nothing but whitespace, you also need to skip those:
for line in wordsf:
if line.isspace(): continue
word = random.choice(line.split())
print(word)
The counting part you have seems to be correct, but unrelated to your question.
Edit: I see you meant something different in your Q (as other A's also intepreted): you want to choose a random line from the file, not a random word from each lines. That being the case, the other A's are correct, but they take O(N)
auxiliary memory for a file of N
lines. There's a nice algorithm due to Knuth to pick a random sample from a stream without knowing in advance how many items it has (unfortunately it requires generating N
random numbers, so it's slower than the simpler one if you have enough memory for the latter... but it's still interesting to consider!-)...:
n = 0
word = None
for line in wordsf:
n += 1
if random.randrange(n) == 0:
word = line
print(word.strip())
Basically, at each line n
, we're picking it to replace the previous one (if any) with a probability of 1.0/n
-- so the first time probability 1 (certainty), the second time probability 0.5, and so on. I'm doing the stripping only at the end as it would be a waste of effort to strip temporary choices that are later replaced; and I'm avoiding the division and floating point hassles by generating a random number with uniform probability between 0 and n-1 included (so the probability of that random number being 0 is 1/n
) -- minor issues, but since they don't make the code any less clear, we might as well take care of them;-).