Help with inverted dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Jul 12 12:23:29 EDT 2005


On Tue, 12 Jul 2005 08:25:50 -0700, rorley wrote:

> OK, so my problem is I have a text file with all of these instances,
> for example 5000 facts about animals.  I need to go through the file
> and put all of the facts (lines) that contain the word lion into a file
> called lion.txt.  If I come across an animal or other word for which a
> file does not yet exist I need to create a file for that word and put
> all instances of that word into that file.  I realize that this should
> probably create 30,000 files or so.  Any help would be REALLY
> appreciated.  Thanks.  Reece

Sounds like homework to me...

Start by breaking the big problem down into little problems:

Step 1: read the data from the file

You do that with something like this:

data = file("MyFile.txt", "r").read()

Notice I said *something like* -- that's a hint that you want to change
that to something slightly different.

Step 2: grab each line, one at a time

Somehow you want to read lines (hint! hint!) from the file, so that you
have a list of text lines in data. How do you read lines (hint!) from a
file in Python?

Once you do that, data should look something like this:

["lions are mammals\n", "lions eat meat\n", "sheep eat grass\n"]

So you can work with each line in data with:

for line in data:
    do_something(line)

Step 3: grab each word from the line

I'll make this one easy for you:

words = line.split()

words now looks like: ["lions", "are", "mammals"]

Step 4: for each word, open a file:

This one is also easy:

for word in words:
    fp = file(word, "w")
    fp.write(all the other words)
    fp.close()

Hint: this code won't quite do what you want. You need to change a few
things.

Does this help? Is that enough to get started? See how far you get, and
then come back for more help.


-- 
Steven.




More information about the Python-list mailing list