I have a text file of a paragraph of writing, and want to iterate through each word in Python – Education Career Blog

How would I do this? I want to iterate through each word and see if it fits certain parameters (for example is it longer than 4 letters..etc. not really important though).

The text file is literally a rambling of text with punctuation and white spaces, much like this posting.

,

Try split()ing the string.

f = open('your_file')
for line in f:
    for word in line.split():
        # do something

If you want it without punctuation:

f = open('your_file')
for line in f:
    for word in line.split():
        word = word.strip('.,?!')
        # do something

,

You can simply content.split()

,


   f = open(filename,"r");
   lines = f.readlines();
   for i in lines:
   thisline = i.split(" ");

,

data=open("file").read().split()
for item in data:
   if len(item)>4:
      print "longer than 4: ",item

Leave a Comment