0

I noticed when I try to iterate over a file with lines such as "python" "please" "work" I only get individual characters back, such as, "p" "y" "t"...

how could I get it to give me the full word? I've been trying a couple hours and can't find a method. I'm using the newest version of python. Edit: All the quotation marks are new lines.

  • I got infuriated and deleted what I had, essentially thought I had the code for the function I was trying to write, I tried storing each element as a substring, then appending it to the list I was trying to make but it didn't work. I'm sorry for not posting an effort though. – Stacks of overflow Nov 13 '12 at 04:19

3 Answers3

3

You can iterate over a file object:

for line in open('file'):
    for word in line.split():
        do_stuff(word)

See the docs for the details: http://docs.python.org/2/library/stdtypes.html#bltin-file-objects

Lester Cheung
  • 1,964
  • 16
  • 17
1

If you are storing the words as a string, you can split the words by space using split function.

>>> "python please work".split(' ')
['python', 'please', 'work']
user1787687
  • 316
  • 3
  • 4
  • 11
  • I was thinking that, but the words are on different lines. Essentially I want it to go to each line and take all the information as one string when I'm iterating, not as characters. – Stacks of overflow Nov 13 '12 at 04:22
  • Can you copy and paste two or three lines of your code? It would be helpful. – user1787687 Nov 13 '12 at 05:14
0

If you have your data in a single string which spans several lines (e.g. it contains '\n' characters), you will need to split it before iterating. This is because iterating over a string (rather than a list of strings) will always iterate over characters, rather than words or lines.

Here's some example code:

text = "Spam, spam, spam.\Lovely spam!\nWonderful spam!"

lines = text.splitlines() # or use .split("\n") to do it manually

for line in lines:
     do_whatever(line)
Blckknght
  • 100,903
  • 11
  • 120
  • 169