简体   繁体   English

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

[英]Output dictionary data dynamically from a python for loop

here, I am trying to spell check a txt file. 在这里,我正在尝试拼写检查txt文件。 first half of my code outputs original (var word) and corrected, if any, (var spell(word)). 我的代码的前半部分输出原始的(变量词)并更正(如果有的话)(变量法术(单词))。 my replacement code uses a data structure like {'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'} . 我的替换代码使用的数据结构为{'zero':'0', 'temp':'bob', 'garbage':'nothing', 'garnvsh': 'garnish'} Now I would like to produce the same data structure from the loop dynamically. 现在,我想从循环中动态生成相同的数据结构。 Can you, please, help me figure it out how to output similar data structure with var word and var spell(word) with first half of the code? 能否请您帮我弄清楚如何在代码的前半部分输出带有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)

我想您想创建一个字典 ,它的键是word ,值是spell(word)

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

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

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