Can';t在Python中使用字典查找和替换文本中的单词
所以我的python脚本应该得到一个文本文件,并基本上使用字典进行翻译,但是我被卡住了,无法让它工作,它运行了,但没有有效地做任何事情 第一个文件(已给出): 我在福特的那门课上的尝试:Can';t在Python中使用字典查找和替换文本中的单词,python,dictionary,Python,Dictionary,所以我的python脚本应该得到一个文本文件,并基本上使用字典进行翻译,但是我被卡住了,无法让它工作,它运行了,但没有有效地做任何事情 第一个文件(已给出): 我在福特的那门课上的尝试: #!/usr/bin/env python # -*- coding: utf-8 -*- class Ford: def __init__ (self, values = dict(), keys = dict()): self.values = values sel
#!/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新手,因此非常感谢您提供的每一点建议和帮助。问题可能在于
Ford
类,从\uuuu init\uu
函数开始:
def __init__ (self, values = dict(), keys = dict()):
self.values = values
self.keys = keys
这里要做的是为value
和key
提供Python默认值,如果函数初始化时没有提供,这两个值都将是空字典。由于您使用fd=Ford(szotar)
初始化Ford
,因此您基本上是在告诉Pythonvalues
是szotar
字典,但是keys
是一个单独的空字典
然后,在fordit
中,使用参数infle
和outFile
初始化函数,但在不使用这些参数的情况下读取和写入文件
最后,即使行text.replace(key,dict()[key])
得到了正确的输入(我不确定它是正确的),它实际上并不是在编辑text
——它必须看起来像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")
请注意,stringreplace方法将替换字符串中出现的所有子字符串。这意味着
sun
会变成nap
,但是sunny
也会变成nappy
您是否收到任何错误消息?(请贴出来。)否则,请解释“没有有效地做任何事情”的意思。实际上,你的代码可能有更多的错误。您正在迭代dict().iterkeys(),但这是一个空dict,因此for循环从不迭代。另外,dict()[key]
保证会抛出一个KeyError
,因为您再次在运行中创建一个空dict,并试图插入它
Ford(szotar, "teszt.txt", "kimenet.txt")