def process_line(line):
has_digit = False
num_sum = 0
new_line = ''
for char in line:
if char.isdigit():
num_sum += int(char)
has_digit = True
else:
new_line += char
if has_digit:
return str(num_sum)
else:
return new_line[::-1]
def process_file(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
for line in infile:
processed_line = process_line(line.strip())
outfile.write(processed_line + '\n')
if __name__ == "__main__":
input_file = 'input.txt'
output_file = 'output.txt'
process_file(input_file, output_file)
优化说明
- 逐行处理:通过
with open
的方式逐行读取文件,避免一次性将整个大文件读入内存,大大降低内存占用。
- 使用生成器和迭代器:代码中
for line in infile
利用了文件对象的迭代器特性,每次只读取一行,而不是读取整个文件内容到列表等数据结构中。
- 简单逻辑处理:在
process_line
函数中,通过一次遍历字符串就完成了是否有数字判断、数字求和以及非数字字符处理,减少了重复遍历字符串的操作。