2015-10-16 153 views
0

我想選擇特定的字符。說文件old.txt包含xxXXyyaasdyyYY。從該文件中只應保留XY並寫入new.txt。 下面的代碼有什麼錯誤?僅保留一個文本文件中的特定字符並將它們寫入新的文本文件

in_file = open("old.txt", "r") 
out_file = open("new.txt","w") 
for line in in_file: 
    out_file.write(line.upper()) 
in_file.close() 
out_file.close() 
+1

我得問爲什麼?這看起來不太直觀。你是否想要計算某些字符被發現的實例的數量?或者是什麼?我認爲你在這裏實際嘗試做的更多細節是有序的。 – KronoS

+3

順便說一句,你應該使用:'with open('old.txt','r')作爲in_file,open('new.txt','w')作爲out_file:'而不是明確地打開和關閉文件。 – KronoS

回答

0

既然你要選擇的字符,你可以一次讀取一個字符。

from collections import defaultdict 

specific_characters = ['X', 'Y'] 
counter_dict = defaultdict(lambda: 0) 

with open("old.txt", "r") as in_file, open("new.txt","a") as out_file: 
    while True: 
    c = in_file.read(1) 
    if not c: 
     break 
    if c in specific_characters: 
     out_file.write(c) 
     counter_dict[c] += 1 

# printing just X and Y for your specific case. 
# the counter will have count of any characters from the specific_characters list. 

print "Count of X: ", counter_dict['X'] 
print "Count of Y: ", counter_dict['Y'] 
+0

@Chris Gruber:我已經用計數器更新了代碼。請立即檢查。 –

0

你可以使用白名單set和上下文管理器(使用with關鍵字),使這個更加地道。

whitelist = {"X", "Y"} 

with open('old.txt') as in_file, 
     open('new.txt', 'w') as out_file: 
    for line in in_file: 
     for letter in line: 
      if letter in whitelist: 
       out_file.write(letter) # no need to uppercase here 
# no need to close either, since we're using the with statement 
1
in_file = open("old.txt", "r") 
out_file = open("new.txt","w") 
for line in in_file: 
    for letter in line: 
    if (letter == 'X') | (letter == 'Y'): 
     out_file.write(letter.upper()) 
in_file.close() 
out_file.close() 
+1

什麼是'X'和'Y'? – sam

+1

謝謝山姆,忘了報價。 – New2Programming

+0

另外,我認爲'X'和'Y'只是一個例子。這些可以是任何字符串。 – sam

相關問題