How to iterate over a space-separated ASCII file in Python

Strange question here.

I have a file .txtthat I want to iterate over. I can get all the words from the array from the file, which is good, but what I want to know how to do is how I can iterate over the whole file, but not the individual letters, but the words themselves.

I want to be able to go through an array in which all the text from the file is located, and basically count all the instances in which the word appears in it.

The only problem is that I do not know how to write code for it.

I tried using a for loop, but it's just iterating over each individual letter when I need whole words.

+3
source share
4 answers

file.txt

f = open("file.txt", "r")
words = f.read().split()
for w in words:
    print w
+10
file = open("test")
for line in file:
    for word in line.split(" "):
         print word
+3

:

def produce_words(file_):
   for line in file_:
     for word in line.split():
        yield word

def main():
   with open('in.txt', 'r') as file_:
      for word in produce_words(file_):
         print word
+1

, - , . , , ( ):

with open('in.txt') as input:
    for line in input:
        for word in line.split():
            ...

, line.split(" "), , line.split() .

with, , .

, , . , itertools.chain.from_iterable :

import itertools
with open('in.txt') as input:
    for word in itertools.chain.from_iterable(line.split() for line in input):
            ...
+1
source

All Articles