On Sunday, March 31, 2013 12:06:18 PM UTC-4, Chris Angelico wrote:
> On Mon, Apr 1, 2013 at 2:52 AM, C.T.
>
> > After playing around with the code, I came up with the following code to
> > get everything into a list:
>
> >
>
> > d=[]
>
> > car_file = open('worstcars.txt', 'r')
>
> > for line in car_file:
>
> > d.append(line.strip('\n'))
>
> > print (d)
>
> > car_file.close()
>
> >
>
> > Every line is now an element in list d. The question I have now is how can
> > I make a dictionary out of the list d with the car manufacturer as the key
> > and a tuple containing the year and the model should be the key's value.
>
>
>
> Ah, a nice straight-forward text parsing problem!
>
>
>
> The question is how to recognize the manufacturer. Is it guaranteed to
>
> be the second blank-delimited word, with the year being the first? If
>
> so, you were almost there with .split().
>
>
>
> car_file = open('worstcars.txt', 'r')
>
> # You may want to consider the 'with' statement here - no need to close()
>
> for line in car_file:
>
> temp = line.split(None, 2)
>
> if len(temp)==3:
>
> year, mfg, model = temp
>
> # Now do something with these three values
>
> print("Manufacturer: %s Year: %s Model: %s"%(mfg,year,model))
>
>
>
> That's sorted out the parsing side of things. Do you know how to build
>
> up the dictionary from there?
>
>
>
> What happens if there are multiple entries in the file for the same
>
> manufacturer? Do you need to handle that?
>
>
>
> ChrisA
Thank you, Chris! I could use slicing and indexing to build the dictionary but
the problem is with the car manufacturer an the car model. Either or both could
be multiple names.
--
http://mail.python.org/mailman/listinfo/python-list