Python turn text file into dictionary

后端 未结 2 612
生来不讨喜
生来不讨喜 2021-01-28 09:18

I\'m writing a spell checking function and I have a text file that looks like this

teh the
cta cat
dgo dog
dya day
frmo from
memeber member

Th

相关标签:
2条回答
  • 2021-01-28 10:12

    You problably want to use split to get the words, then map the misspelled word to the correctly spelled one:

    def spell():
      dictCorrect={}
      with open('autoCorrect.txt','r') as corrections:        
        for line in corrections:
          wrong, right = line.split(' ')
          dictCorrect[wrong] = right
      return dictCorrect
    
    0 讨论(0)
  • 2021-01-28 10:22

    Use this:

    with open('dictionary.txt') as f:
        d = dict(line.strip().split(None, 1) for line in f)
    

    d is the dictionary.

    disclaimer: This will work for the simple structure you have illustrated above, for more complex file structures you will need to do much more complex parsing.

    0 讨论(0)
提交回复
热议问题