populating a python dictionary with text file

I am trying to populate a python dictionary by looping through the file. The text file reads like so:

Gen 1:1 "some text"
Gen 1:2 "some more text"

I am trying to populate the dictionary-making the key being the reference "Gen 1:1" and so on.

Please point me in the right direction. I am willing to do the foot work.

1 answer

  • answered 2021-11-23 03:10 asiloisad

    You didn't provide much information about the file structure, but it looks like regular expressions might be a good solution.

    >>> import re
    >>> path = '<path.to.the.file>'
    >>> with open(path, 'r') as f:
    >>>     lines = f.readlines()
    >>> rex = re.compile(r'(Gen \d+:\d+) +\"(.*)\"')
    >>> data = {}
    >>> for line in lines:
    >>>     match = rex.match(line)
    >>>     if match:
    >>>         data[match[1]] = match[2]
    >>> data
    {'Gen 1:1': 'some text', 'Gen 1:2': 'some more text'}
    

    you can test above regular expression at: https://regex101.com/r/6vDT9w/1

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum