所以我的python脚本应该得到一个文本文件并基本上使用字典翻译它,但我被卡住了,无法让它工作,它运行但没有做任何有效的事情。
第一个文件(已给出):
# -*- coding: utf-8 -*-
from bead import Ford
szotar = {"The" : "A", "sun": "nap", "shining" : "süt", "wind" : "szél", "not" : "nem", "blowing" : "fúj"}
fd = Ford(szotar)
fd.fordit("teszt.txt", "kimenet.txt")
我对福特班的尝试:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Ford:
def __init__ (self, values = dict(), keys = dict()):
self.values = values
self.keys = keys
def fordit(self, inFile, outFile):
self.inFile = inFile
self.outFile = outFile
try:
with open("teszt.txt", 'r') as inFile:
text = inFile.read()
except:
print "Nincs input file!"
for key in dict().iterkeys():
text.replace(key,dict()[key])
outFile = open("kimenet.txt", "w")
outFile.write(text)
outFile.close()
我是python的新手,所以非常感谢每一点建议和帮助。
答案 0 :(得分:1)
问题可能在于Ford
类,从__init__
函数开始:
def __init__ (self, values = dict(), keys = dict()):
self.values = values
self.keys = keys
您正在做的是为value
和keys
提供Python默认值,如果在初始化函数时未提供,则这两个默认值都是空字典。由于您使用Ford
初始化fd = Ford(szotar)
,因此您基本上告诉Python values
是szotar
字典,但keys
是一个单独的空字典。
然后,在fordit
中,使用参数inFile
和outFile
初始化函数,然后在不使用这些参数的情况下读取和写入文件。
最后,即使行text.replace(key,dict()[key])
获得了正确的输入(我不确定它),它实际上并没有编辑text
- 它必须看起来像{{ 1}}而不是。仅此行就意味着具有替换文本或没有替换文本的输出文件之间的差异。
我会重写你定义text = text.replace(key,dict()[key])
类的整个文件,如下所示:
Ford
你也可以避免手动调用子功能#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Ford():
def __init__ (self, words):
self.words = words
def fordit(self, inFile, outFile):
with open(inFile, 'r') as iF:
text = iF.read()
for key in self.words:
text = text.replace(key, self.words[key])
with open(self.outFile, "w") as oF:
oF.write(text)
,让它看起来像这样:
fordit
然后第一个文件只需要底部的这一行,而不是你现在拥有的那一行:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Ford():
def __init__ (self, words, inFile, outFile):
self.words = words
self.inFile = inFile
self.outFile = outFile
self.fordit()
def fordit(self):
with open(self.inFile, 'r') as iF:
text = iF.read()
for key in self.words:
text = text.replace(key, self.words[key])
with open(self.outFile, "w") as oF:
oF.write(text)
请注意,字符串替换方法将替换字符串中子字符串的所有次出现。这意味着Ford(szotar, "teszt.txt", "kimenet.txt")
会变成sun
,但nap
也会变成sunny
。