【问题标题】:How can I extract a floating point value from a string, in python 3?如何在 python 3 中从字符串中提取浮点值?
【发布时间】:2020-07-13 03:12:23
【问题描述】:

字符串 = 概率为 0.05 如何在变量中提取 0.05 浮点值?文件中有很多这样的字符串,我需要求平均概率,所以 我使用了“for”循环。 我的代码:

fname = input("enter file name: ")
fh = open(fname)
count = 0
val = 0
for lx in fh:
    if lx.startswith("probability"):
        count = count + 1
        val = val + #here i need to get the only "float" value which is in string
print(val)

【问题讨论】:

标签: python python-3.x string file extract


【解决方案1】:
import re
string='probability is 1'
string2='probability is 1.03'
def FindProb(string):

    pattern=re.compile('[0-9]')
    result=pattern.search(string)
    result=result.span()[0]

    prob=string[result:]
    return(prob)

print(FindProb(string2))

好的,所以。 这是使用正则表达式(又名 Regex aka re)库

它基本上建立了一个模式,然后在一个字符串中搜索它。 该函数接受一个字符串并找到字符串中的第一个数字,然后返回变量 prob,它是从第一个数字到结尾的字符串。

如果您需要多次查找概率,则可以这样做:

import re
string='probability is 1'
string2='probability is 1.03 blah blah bllah probablity is 0.2 ugggggggggggggggg probablity is 1.0'
def FindProb(string):
    amount=string.count('.')
    prob=0
    for i in range(amount):
        pattern=re.compile('[0-9]+[.][0-9]+')
        result=pattern.search(string)
        start=result.span()[0]
        end=result.span()[1]

        prob+=float(string[start:end])
        string=string[end:]
    return(prob)

print(FindProb(string2))

对此需要注意的是,所有内容都必须有一个句点,因此 1 必须是 1.0,但这应该不是太大的问题。如果是,请告诉我,我会设法找到方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多