Welcome to Dream.In.Code
Getting Help is Easy!

Join 135,963 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,529 people online right now. Registration is fast and FREE... Join Now!




How to read word by word from a file using python?

 
Reply to this topicStart new topic

How to read word by word from a file using python?

gijig
14 May, 2008 - 09:35 AM
Post #1

New D.I.C Head
*

Joined: 14 May, 2008
Posts: 5

I am a beginner in python. I need help from you guys. If possible give me the sites for some python codes.
User is offlineProfile CardPM
+Quote Post

Moezzie
RE: How To Read Word By Word From A File Using Python?
24 Jun, 2008 - 03:41 PM
Post #2

New D.I.C Head
*

Joined: 25 Nov, 2007
Posts: 44


My Contributions
The easies way i can think of is reading the hole file (or line by line) into a string and then splitting the it at every space. You will end up with a list containing all the words in file.

I would do this with the split() function. You can read about it here:
http://docs.python.org/lib/string-methods.html
User is offlineProfile CardPM
+Quote Post

ibbie
RE: How To Read Word By Word From A File Using Python?
7 Jul, 2008 - 09:29 AM
Post #3

New D.I.C Head
Group Icon

Joined: 7 Jul, 2008
Posts: 8


Dream Kudos: 75
My Contributions
Quick and dirty, assumes there's a file in the current working directory called "test.txt"

CODE
--($:~)-- cat test.txt
This line is split into words.


CODE
def getwords(file):
    """
    >>> for word in getwords('test.txt'):
    ...     print 'word: %s' % word
    ...
    word: This
    word: line
    word: is
    word: split
    word: into
    word: words.
    """

    f = open(file, 'r')
    for line in f:
        for word in line.split(' '):
            yield word.strip()



A good google search would be "python iterate over file"
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 09:35AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month