从python for循环动态输出字典数据

时间:2016-09-05 16:22:11

标签: python

在这里,我正在尝试拼写检查txt文件。我的代码的前半部分输出原始(var word)并更正(如果有的话)(var spell(word))。我的替换代码使用像{'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'}这样的数据结构。现在我想动态地从循环中生成相同的数据结构。您能否帮助我弄清楚如何使用var wordvar spell(word)输出与前半部分代码类似的数据结构?

import os, os.path
from textblob import TextBlob
from autocorrect import spell
import fileinput
import json

data = []

with open("input.txt", "r") as my_file:
    for line in my_file.readlines():
        zen = TextBlob(line)
        for word in zen.words:
            word, spell(word)

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'}

with open('../input.txt') as infile, open('../output.txt', 'w') as outfile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        outfile.write(line)

1 个答案:

答案 0 :(得分:1)

我想你想create dictionary其密钥为word且值为spell(word)

my_dict = { word: spell(word) for word in zen.words }