因此,我的Python腳本應該獲取文本文件,並且基本上使用字典對其進行翻譯,但是我被卡住了,無法使其工作,它運行但沒有有效地做任何事情。無法在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()
我是新來的蟒蛇,所以建議和幫助的每一位非常感謝。
您是否收到任何錯誤訊息? (請張貼它。)否則,解釋什麼「_doesn't做任何有效_」的意思。 – DyZ
[爲什麼不調用Python字符串方法可以做任何事,除非你指定它的輸出?](http://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method- do-anything-unless-you-assign-its-out) –
實際上,你的代碼有更多的錯誤。你正在遍歷'dict()。iterkeys()',但這是一個空的字典,所以for循環永遠不會迭代。此外,'dict()[key]'保證會拋出一個'KeyError',因爲你再次創建一個空字典,並嘗試將其解壓縮到它 –