简体   繁体   English

Python将文本文件转换为字典

[英]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. 我知道我想让我的函数做什么,但无法弄清楚如何执行它。

Use this: 用这个:

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

d is the dictionary. d是字典。

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. 免责声明:这将适用于您上面说明的简单结构,对于更复杂的文件结构,您将需要执行更复杂的解析。

You problably want to use split to get the words, then map the misspelled word to the correctly spelled one: 您可能想使用split来获取单词,然后将拼错的单词映射到正确拼写的单词:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM