2013-07-16 38 views
0

我正在寫一個拼寫檢查功能,我有一個文本文件,它看起來像這樣Python的轉文本文件導入詞典

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

的不正確的拼寫是在左邊(這將是我的鑰匙)和正確的拼寫在右邊(我的價值)。

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

我知道我想讓我的功能做,但無法弄清楚如何執行它。

+0

你有沒有考慮使用[算法](http://en.wikipedia.org /維基/ Levenshtein_distance)呢?如果你建立了這個,你可以看到多麼接近的單詞,你可以建立一個只包含所有單詞的文本文件。你所要做的就是挑選匹配最好的文字 –

回答

5

使用此:

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

d是字典。

免責聲明: 這將爲你在上面所示,你需要做更多複雜的分析更復雜的文件結構,結構簡單,工作。

+1

Ack!只需幾秒鐘就能擊敗我! (有+1) – inspectorG4dget

+1

@ inspectorG4dget這就是所需要的:) –

+0

謝謝!有沒有辦法擺脫新的行字符? {'teh':'\ n','frmo':'from \ n','dgo':'dog \ n','cta':'cat \ n','memeber':'member',' dya':'day \ n'} – user2553807

0

您problably要使用拆分得到的話,則拼錯的單詞映射到正確拼寫的一個:

def spell(): 
    dictCorrect={} 
    with open('autoCorrect.txt','r') as corrections:   
    for line in corrections: 
     wrong, right = line.split(' ') 
     dictCorrect[wrong] = right 
    return dictCorrect