我想选择一个特定的角色。假设文件old.txt
包含xxXXyyaasdyyYY
。在该文件中,只应保留X
和Y
并将其写入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()
答案 0 :(得分: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 :(得分: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
答案 2 :(得分: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']