[Tutor] Trying to enter text from a file to a Dictionary
Bob Gailer
bgailer at alum.rpi.edu
Fri Jan 27 18:42:42 CET 2006
Alan Gauld wrote:
> Hi Ben,
>
>
>> I want to enter the words and definitions from the text file into the
>> dict.
>> The way the text file is set up is that one line is the word and the
>> next line is the definition.
>>
>
>
>> I tried using a for loop like this
>>
>> f = open('glossary.txt','r')
>> gloss = {}
>>
>> for line in f:
>> gloss[line] = line
>>
>
> The problem that you have is that you really need to read two lines at a
> time.
> (Assuming that the definitions are all on one line which may not be true!)
> A while loop may be easier in this case.
>
> A for loop will read each line individually. You then need to set a
> definition
> flag to tell the loop body whether you are reading a definition or a key.
>
> Either type of loop is possible. Since you started with a for loop lets
> stick with it...
>
> definition = False
> currentKey = None
>
> for line in f:
> if isDefinition:
> gloss[currentKey] = line
> currentKey = None
> isDefinition = False
> else:
> currentKey = line
> isDefinition = True
>
Or you can use next():
for line in f:
gloss[line] = f.next()
> If the definitions take up more than one line each then you will need to
> think
> about how to identify the end of a definition - a blank line maybe? You will
> need to append the lines to the glossary entry (rather than just assign
> them)
> until the end of the definition. And you will need to update the
> isDefinition
> flag at the appropriate times.
>
> HTH,
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
More information about the Tutor
mailing list