You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7爬虫:提取浮点数字并计算总和的实现方案

Solution for Processing Floats and Calculating Sum in Python 2.7

Hey there! Since you're already set up with Python 2.7 and have re imported (which is exactly what we need here), let's walk through how to clean your string and compute the total sum step by step.

Step 1: Extract & Clean the Floating-Point Numbers

Your input string has [数字] suffixes attached to each float—we can handle this in two simple ways using regex:

Approach 1: Strip the Bracket Suffixes

We'll use re.sub() to remove all instances of [数字], then split the cleaned string into individual float strings:

import re

# Your original input content
input_str = "9.27[7] 9.25[8] 10.17[9] 10.72[10]"

# Remove all [number] patterns from the string
cleaned_str = re.sub(r'\[\d+\]', '', input_str)
# Split into a list of float strings (automatically handles extra spaces)
float_strings = cleaned_str.split()

# Convert strings to float values and calculate the total sum
float_values = [float(s) for s in float_strings]
total_sum = sum(float_values)

# Output the results
print("Cleaned floats:", ' '.join(float_strings))
print("Total sum:", total_sum)

Approach 2: Directly Match Floats

If you prefer to target the floating-point numbers directly, re.findall() will grab all sequences of digits with a decimal point:

import re

input_str = "9.27[7] 9.25[8] 10.17[9] 10.72[10]"

# Extract all floating-point numbers as strings
float_strings = re.findall(r'\d+\.\d+', input_str)
# Convert to float values and compute the sum
float_values = [float(s) for s in float_strings]
total_sum = sum(float_values)

# Print results
print("Cleaned floats:", ' '.join(float_strings))
print("Total sum:", total_sum)

What You'll Get

  • Both methods will output your desired cleaned format: 9.27 9.25 10.17 10.72
  • The sum calculation will return 39.41 (9.27 + 9.25 + 10.17 + 10.72 = 39.41)

Either approach works perfectly—pick whichever feels more intuitive for your workflow!

内容的提问来源于stack exchange,提问作者clemens heiderer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:44:49