import concurrent.futures
import os
def calculate_weighted_sum(file_path):
weighted_sum = 0
total_weight = 0
try:
with open(file_path, 'r') as file:
for position, line in enumerate(file, start=1):
try:
value = float(line.strip())
weighted_sum += value * position
total_weight += position
except ValueError:
pass
except FileNotFoundError:
pass
except PermissionError:
pass
return weighted_sum, total_weight
def calculate_weighted_average(file_paths):
total_weighted_sum = 0
total_total_weight = 0
with concurrent.futures.ProcessPoolExecutor() as executor:
results = list(executor.map(calculate_weighted_sum, file_paths))
for weighted_sum, total_weight in results:
total_weighted_sum += weighted_sum
total_total_weight += total_weight
if total_total_weight == 0:
return 0
return total_weighted_sum / total_total_weight
if __name__ == '__main__':
file_paths = []
for root, dirs, files in os.walk('.'):
for file in files:
file_path = os.path.join(root, file)
file_paths.append(file_path)
average = calculate_weighted_average(file_paths)
print(f"The weighted average is: {average}")
- calculate_weighted_sum函数:
- 该函数用于计算单个文件中数值的加权和以及总权重。
- 它尝试打开文件,并逐行读取其中的数值。
- 对于每一行,尝试将其转换为浮点数,如果转换成功,则计算加权值并累加到
weighted_sum
中,同时将位置权重累加到total_weight
中。
- 处理文件不存在(
FileNotFoundError
)和权限不足(PermissionError
)等异常情况。
- calculate_weighted_average函数:
- 使用
ProcessPoolExecutor
创建进程池,并行处理所有文件路径。
- 对每个文件调用
calculate_weighted_sum
函数,并收集结果。
- 遍历结果,累加加权和和总权重,最后计算并返回加权平均数。
- 主程序部分:
- 使用
os.walk
获取当前目录及其子目录下的所有文件路径。
- 调用
calculate_weighted_average
函数计算加权平均数并打印结果。
if __name__ == '__main__'
语句用于确保在多进程环境下代码的正确执行,特别是在Windows系统上。