如何从.txt文件中提取浮点值以用于python中的计算?

2024-06-01 10:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        count = count + 1
print(count)

有一个包含27行的文件,比如X-DSPAM-Confidence:0.xxxxx,我需要从每个行中提取数值以用于计算。你知道吗


Tags: nameinforinputifcountlineopen
3条回答

只要格式与您描述的完全一致,就可以使用以下代码:

float(line.split(':')[1])

如果文本中的变化比您描述的更多,您可能需要尝试regex。你知道吗

您可以使用str.rfind(':')来获取:的位置,然后执行字符串切片来获取值。你知道吗

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        value = line[line.rfind(':'):]  # will take the last occurrence of : to slice the line
        print(value)
        count = count + 1
print(count)

尝试使用split(':')

代码:

count = 0
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
    if line.startswith("X-DSPAM-Confidence:") :
        print(line)
        value = line.split(':')[-1]  # will split line into 'X-DSPAM-Confidence' and 'value'
        # if you have ',' at the end of the line, simply do this:
        value = value.strip(',')
        value = float(value)
        print(value)
        count = count + 1
print(count)

相关问题 更多 >