Python 把文本文件转换成字典

2024-09-28 01:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个拼写检查函数,我有一个文本文件,看起来像这样

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

错误的拼写在左边(这将是我的键),正确的拼写在右边(我的值)。在

^{pr2}$

我知道我想要我的函数做什么,但不知道如何执行它。在


Tags: the函数from错误catmember文本文件dog
2条回答

您可能希望使用split来获取单词,然后将拼写错误的单词映射到拼写正确的单词:

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

使用这个:

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

d是字典。在

免责声明: 对于上面所示的简单结构,这是有效的,对于更复杂的文件结构,您将需要执行更复杂的解析。在

相关问题 更多 >

    热门问题