2013-12-22 74 views
1

我的目標是編寫一個需要兩個字符串和兩個文件名的函數。該函數將第一個文件中的第一個字符串替換爲第二個字符串。之後,它將內容寫入第二個文件。這就是我所做的:替換文檔中的單詞

def sed(s1, s2, f1, f2): 
    try: 
     fin1 = open(f1,'r') 
     fin2 = open(f2, 'w') 
     for word in fin1: 
      if word == s1: 
       word = s2 
       fin2.write(word) 
      else: 
       fin2.write(word) 
    except: 
     'something went wrong' 

但是,替換部分並沒有很好的工作。第一個字符串沒有被第二個字符串替換。我知道在Python中有一個.replace,但我想爲自己的練習編寫自己的替換函數。

+3

'在fin1中的單詞:'逐行讀取文件,而不是逐字讀取 –

+0

How我可以讓它逐字閱讀嗎? – user1691278

+0

而不是你有什麼,我可以推薦'除了例外作爲e:sys.exit(「錯誤的東西:」+ str(e))''。這樣你可以真正看到具體發生了什麼問題。在實踐中,你應該捕獲特定的錯誤,比如'OSError'或者'IOError',這樣其他意外的錯誤,比如'AttributeError'或者'TypeError',不會神祕地讓你陷入瘋狂的追逐。 – SethMMorton

回答

1

從線使用str.split()

for line in fin1: 
    for word in line.split(): 
+2

這個問題的一個問題是,它將在默認情況下在空白處分割,單詞將包括尾隨逗號和句號。 – Totem

+0

也是如此,但仍然值得一提,因爲這個原因 – Totem

-1

不使用內置的方式,一種是任務一樣,這是不是一個好主意,因爲你的事情複雜了許多帶話。我假設你不想使用正則表達式操作模塊're'要麼...所以找到我的答案在下面。這可以寫少線,但這種方式更具有可讀性:

def replace_string(string1, string2, file1, file2): 
    with open(file1, 'r') as first_file: 
    my_lines = [] 
    for line in first_file.readlines(): 
     if string1 in line: 
     for word in line.split(string1): 
      if word != string1: 
      if (word and '\n' not in word): 
       new_word = word+string2 
      else: 
       new_word = word 
      my_lines.append(new_word) 
     else: 
     my_lines.append(line) 
    with open(file2, 'w') as second_file: 
    for item in my_lines: 
     second_file.write(item) 

比方說,你有「first_file.txt」,看起來像這樣:

This is my first line. It contains the words: cat, dog, fish, cat. 
This is the second line. cat. ‘cat’ is a pet 
This is the third line. cat...cat cat. 
You have hopefully replaced all occurrences of *cat*cat 

而且要替換字符串「 cat'與'new_cat'並保存到'second_file.txt'文件中。您不需要創建second_file.txt,它只會在您運行代碼的相同位置創建。

replace_string('cat', 'new_cat', 'first_file.txt', 'second_file.txt') 

你的第二個文件將是這樣的:

This is my first line. It contains the words: new_cat, dog, fish, new_cat. 
This is the second line. new_cat. ‘new_cat’ is a pet 
This is the third line. new_cat...new_cat new_cat. 
You have hopefully replaced all occurrences of *new_cat*new_cat 

當然,這是不完美的。如果你在文件'catcat'中有一個單詞會發生什麼......你想忽略它嗎?或者你想把它變成'new_catnew_cat'?這個代碼將它變成'new_cat'只...所以這裏有另一個條件來檢查,等等...