繁体   English   中英

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

[英]Extract float number from a string and add them together. (python)

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

我有多个这样的数据,我想从该文本中提取浮点数。 然后,我想将它们全部加在一起。 我怎么能go一下实现呢?

编辑; 给出的例子来自这个文本文件,我已经提取了这些部分,但现在我想提取数字只把它们加在一起。 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM