2015-10-16 158 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

相关问题