text file to dictionary

Thread Solved

Join Date: Mar 2009
Posts: 10
Reputation: lilkid is an unknown quantity at this point 
Solved Threads: 0
lilkid lilkid is offline Offline
Newbie Poster

text file to dictionary

 
0
  #1
Mar 27th, 2009
test.txt

ok i want to read this file into a dictionary and this is the output
d={"flight":T34712, From:ABERDEEN, scheduled 0800, remark landed}
etc

flight is the key

do i have to parse the text file i know i cant put it straight into the dictionary as i get this output {flightfromscheduledremark: whole file}
if i have to parse it can anyone give me a couple of links please.

or can i read the text file word by word and use a while loop like

while (not end of file)
if word is first in sentance
d.append{flight:test}

heres my code currently if anyone wants to look and criticise.

  1. #!/usr/bin/env python
  2. import HTMLParser
  3. class MyParser(HTMLParser.HTMLParser):
  4.  
  5.  
  6. ########################################################
  7. def __init__(self):
  8. HTMLParser.HTMLParser.__init__(self)
  9. self.titleFound = False
  10. return
  11.  
  12. ########################################################
  13. def handle_starttag(self, tag, attrs)
  14.  
  15. if tag == 'td':
  16.  
  17. self.titleFound = True
  18. return
  19.  
  20. ##########################################################
  21. def handle_data(self, titleString):
  22.  
  23. if self.titleFound == True:
  24. filename = "test.csv"
  25. f = open(filename, 'a')
  26. f.write(titleString)
  27. f.close()
  28.  
  29. return
  30.  
  31. ##########################################################
  32. def handle_endtag(self, tag):
  33.  
  34. if tag == 'td':
  35. self.titleFound = False
  36. return
  37.  
  38. ###################End of Class definition #######################
  39. if __name__ == '__main__':
  40. titleExtractor = MyParser()
  41. buffer = open('live.html', 'r').read()
  42. titleExtractor.feed(buffer)
  43.  
  44.  
  45. filename = "test.csv"
  46. f = open(filename,'r')
  47. test = f.read()
  48.  
  49. d={"flight":test}
  50. print d
Last edited by lilkid; Mar 27th, 2009 at 2:48 pm.
Reply With Quote Quick reply to this message  
Join Date: May 2008
Posts: 1,018
Reputation: Paul Thompson has a spectacular aura about Paul Thompson has a spectacular aura about Paul Thompson has a spectacular aura about 
Solved Threads: 167
Paul Thompson's Avatar
Paul Thompson Paul Thompson is offline Offline
Veteran Poster

Re: text file to dictionary

 
0
  #2
Mar 27th, 2009
You can read the text file word by word!
  1. d = {'flight':[]}
  2. f = #text file
  3. for line in f:
  4. for word in line.split():
  5. if word == what_you_want:
  6. d['flight'].append(word)
Hows that? Im a bit confused by exactly what you want but that will read a text file by each word. Replace the if statement with your own one that does something more relevant.
Make it idiot-proof, and someone will just make a better idiot
Check out my Site | and join us on IRC | Python Specific IRC
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 10
Reputation: lilkid is an unknown quantity at this point 
Solved Threads: 0
lilkid lilkid is offline Offline
Newbie Poster

Re: text file to dictionary

 
0
  #3
Mar 27th, 2009
T34712 ABERDEEN 0800 LANDED 08:00
BE171 SOUTHAMPTON 0820 LANDED 08:07

here are 2 lines in the txt file i want to put it into a dictionary so the output is

d={"flight":T34712, From:ABERDEEN, scheduled 0800, remark landed}
d={"flight":BE171 , From: SOUTHAMPTON, scheduled 0820, remark landed}

with flights as the dictionary key

thanks for your suggestion ill try it out and reply tomorrow
Last edited by lilkid; Mar 27th, 2009 at 5:43 pm.
Reply With Quote Quick reply to this message  
Join Date: Jul 2007
Posts: 495
Reputation: shadwickman will become famous soon enough shadwickman will become famous soon enough 
Solved Threads: 76
shadwickman's Avatar
shadwickman shadwickman is offline Offline
Posting Pro in Training

Re: text file to dictionary

 
0
  #4
Mar 27th, 2009
EDIT: The below isn't too helpful as vegaseat posted a better (and full) verison.

What do you mean by
  1. d={"flight":T34712, From:ABERDEEN, scheduled 0800, remark landed}

The other keys need to be enclosed in quotes to, so that
  1. d['flight'] = 'T34712'
  2. d['from'] = 'ABERDEEN'
  3. #etc...

The best solution I think is paulthom12345's suggestion. Although, I'm still confused about the set-up you seem to want. There's a better way to organize it, such as one list with each index a separate flight, and each of those indices holding a dict with the keys for 'flight', 'from', 'scheduled', 'remark', etc. Like:
  1. flights = [
  2. { 'flight': 'T34712', 'from': 'ABERDEEN', 'scheduled': 0800, 'remark': 'LANDED 08:00 ' },
  3. { 'flight': 'BE171', 'from': 'SOUTHAMPTON', 'scheduled': 0820, 'remark': 'LANDED 08:07 ' }
  4. ]
OR
  1. flights = {
  2. 'T34712': { 'from': 'ABERDEEN', 'scheduled': 0800, 'remark': 'LANDED 08:00 ' },
  3. 'BE171': { 'from': 'SOUTHAMPTON', 'scheduled': 0820, 'remark': 'LANDED 08:07 ' }
  4. ]
using the flight number as a key in the dict, and it's value as a dict with the other info.
Last edited by shadwickman; Mar 27th, 2009 at 7:32 pm.
"Two good old boys in a fire-apple red convertible. Stoned. Ripped. Twisted. Good people."
- Hunter S. Thompson
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,666
Reputation: vegaseat is a glorious beacon of light vegaseat is a glorious beacon of light vegaseat is a glorious beacon of light vegaseat is a glorious beacon of light vegaseat is a glorious beacon of light 
Solved Threads: 1091
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: text file to dictionary

 
0
  #5
Mar 27th, 2009
If I understand you right, it should look like this ...
  1. # assumed test data (text from a data file)
  2. data_str = """\
  3. T34712 ABERDEEN 0800 LANDED 08:00
  4. BE171 SOUTHAMPTON 0820 LANDED 08:07"""
  5.  
  6. # first create a list of lists
  7. data_list = [line.split() for line in data_str.split('\n')]
  8. print data_list
  9.  
  10. """
  11. my prettied up result -->
  12. [
  13. ['T34712', 'ABERDEEN', '0800', 'LANDED', '08:00'],
  14. ['BE171', 'SOUTHAMPTON', '0820', 'LANDED', '08:07']
  15. ]
  16. """
  17.  
  18. # now create a list of dictionaries
  19. dict_list = []
  20. data_dict = {}
  21. for line in data_list:
  22. sf = "%s, From:%s, scheduled %s, remark %s"
  23. value = sf % (line[0], line[1], line[2], line[3])
  24. data_dict['flight'] = value
  25. dict_list.append(data_dict)
  26. # start dictionary over
  27. data_dict = {}
  28.  
  29. print(dict_list)
  30.  
  31. """
  32. my prettied up result -->
  33. [
  34. {'flight': 'T34712, From:ABERDEEN, scheduled 0800, remark LANDED'},
  35. {'flight': 'BE171, From:SOUTHAMPTON, scheduled 0820, remark LANDED'}
  36. ]
  37. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 10
Reputation: lilkid is an unknown quantity at this point 
Solved Threads: 0
lilkid lilkid is offline Offline
Newbie Poster

Re: text file to dictionary

 
0
  #6
Mar 27th, 2009
sorry for the confusion guys

basically i want to read the test.txt data into a dictionary

d={"flight":BE171 , From: SOUTHAMPTON, scheduled 0820, remark landed}

where d is the dictionary

so that in future i can search thy dictionary by imputting BE171 etc hich outputs that key

does this make sense.

ive got something to work with now. ill post back when i have implemented the solution.

looks like i have to work on my making sense skills.
Last edited by lilkid; Mar 27th, 2009 at 7:49 pm.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 1614 | Replies: 5
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2010 DaniWeb® LLC