从字符串中提取浮点数并将它们相加.(python)


X-DSPAM-Confidence:    0.8475
X-DSPAM-Confidence:    0.6735
X-DSPAM-Confidence:    0.5474
X-DSPAM-Confidence:    0.8375

我有多个这样的数据,我想从文本中提取浮点数。然后,我想把它们都加起来。我怎样才能做到这一点呢?

编辑;给出的例子来自这个文本文件,我已经提取了这些部分,但现在我想提取数字,只是把它们加在一起。https://www.py4e.com/code3/mbox-short.txt?PHPSESSID=bbcdb4b3754dc70f9a331ecab6057a7e

如果都是相同的格式,那么您可以简单地执行:

strings = ["X-DSPAM-Confidence: 0.8475", "X-DSPAM-Confidence: 0.6735", "X-DSPAM-Confidence: 0.5474", "X-DSPAM-Confidence: 0.8375"] #Split after ": " gives ["X-DSPAM-Confidence","0.8475"] for the first string
#Take the last number index in each splittet string i.e "0.8475" and convert to a number
vals = [float(p.split(": ")[1]) for p in strings] #[0.8475, 0.6735, 0.5474, 0.8375]
sum(vals) #2.9059

您可以简单地用"X-DSPAM-Confidence: "split字符串。假设你有一些换行符或空格,你可以使用.strip来删除它们

x = """X-DSPAM-Confidence:    0.8475
X-DSPAM-Confidence:    0.6735
X-DSPAM-Confidence:    0.5474
X-DSPAM-Confidence:    0.8375"""
result = sum([float(i.strip()) for i in x.split("X-DSPAM-Confidence:") if i.strip()])
mystring = ['X-DSPAM-Confidence: 0.8475','X-DSPAM-Confidence: 0.6735','X-DSPAM- 
Confidence: 0.5474','X-DSPAM-Confidence: 0.8375']
res = [float(m.split(": ")[1])for m in mystring]
sum(res)

如果你的字符串顺序相同,那么把它们作为一个列表形式的字符串,并应用这个,它将从每个字符串中获取最后一个索引并将其存储为浮点数,最后它将添加其中的所有元素

这是你需要的

txt = """X-DSPAM-Confidence:    0.8475
X-DSPAM-Confidence:    0.6735
X-DSPAM-Confidence:    0.5474
X-DSPAM-Confidence:    0.8375"""
values = [float(value) for value in txt.replace("X-DSPAM-Confidence:    ", "").replace("t", "").replace("    ", "").split("n")]
print(values)

最新更新