2017-05-05 70 views
-1

因此,我的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() 

我是新來的蟒蛇,所以建議和幫助的每一位非常感謝。

+0

您是否收到任何錯誤訊息? (請張貼它。)否則,解釋什麼「_doesn't做任何有效_」的意思。 – DyZ

+1

[爲什麼不調用Python字符串方法可以做任何事,除非你指定它的輸出?](http://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method- do-anything-unless-you-assign-its-out) –

+0

實際上,你的代碼有更多的錯誤。你正在遍歷'dict()。iterkeys()',但這是一個空的字典,所以for循環永遠不會迭代。此外,'dict()[key]'保證會拋出一個'KeyError',因爲你再次創建一個空字典,並嘗試將其解壓縮到它 –

回答

1

的問題可能是在您的__init__功能在於Ford類首發:

def __init__ (self, values = dict(), keys = dict()): 
    self.values = values 
    self.keys = keys 

你的valuekeys那裏所做的事情是給Python的默認值,這都將是空的字典如果沒有提供當函數初始化時。由於您正在使用fd = Ford(szotar)初始化Ford,因此您基本上告訴Python valuesszotar字典,但keys是單獨的空字典。

然後,在fordit中,您使用參數​​和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") 

注意,字符串替換方法將取代所有出現的子字符串中的。這意味着sun會變成nap,但sunny也會變成nappy

相關問題