user2553807
user2553807

Reputation: 329

Python turn text file into dictionary

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

The incorrect spelling is on the left (which will be my key) and the correct spelling is on the right (my value).

def spell():
    corrections=open('autoCorrect.txt','r')
    dictCorrect={}
    for line in corrections:
        corrections[0]=[1]
        list(dictCorrect.items())

I know what I want my function to do but can't figure out how to execute it.

Upvotes: 0

Views: 1837

Answers (2)

jh314
jh314

Reputation: 27792

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

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43447

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.

Upvotes: 5

Related Questions