MST

星途 面试题库

面试题:Python字符串专家难度操作题

假设你有一个非常大的文本文件,里面每行都是一个字符串。要求你编写一个Python程序,实现以下功能:1. 逐行读取文件内容,对于每一行字符串,如果它包含数字(0 - 9中的任意一个),则提取出所有数字并计算它们的和。2. 如果该行字符串不包含数字,则将其反转。3. 将处理后的每行结果写入到一个新的文件中。请考虑优化方案,以提高处理大文件时的效率,并写出完整的Python代码。
45.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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)

优化说明

  1. 逐行处理:通过with open的方式逐行读取文件,避免一次性将整个大文件读入内存,大大降低内存占用。
  2. 使用生成器和迭代器:代码中for line in infile利用了文件对象的迭代器特性,每次只读取一行,而不是读取整个文件内容到列表等数据结构中。
  3. 简单逻辑处理:在process_line函数中,通过一次遍历字符串就完成了是否有数字判断、数字求和以及非数字字符处理,减少了重复遍历字符串的操作。