【问题标题】:I've a problem about printing file in python我有一个关于在 python 中打印文件的问题
【发布时间】:2020-12-04 12:16:58
【问题描述】:

我想从通过line.startswith() 找到的文件中打印一些数字,但我想对它们求和,它们是字符串而不是浮点数,所以我无法添加它们。如何将它们转换为浮点数。

这是我的代码:

    file='mbox.txt'
    handle=open(file)
    count=0
    for line in handle:
        if line.startswith('X-DSPAM-Confidence:'):
            count=count+1
            numeri(line[20:])
            num='%g'%float(numeri.strip(' \n '))
            n=sum(num)
    print('Le stringhe che iniziano con "X-DSPAM-Confidence:" sono' ,count)
    print(n)

对不起,英语和编码错误,但我在这方面很新

【问题讨论】:

  • 使用num='%g'%float(numeri.strip(' \n ')) 将其转换回字符串。只需使用num = float(numeri.strip())

标签: python python-3.x file printing


【解决方案1】:

Hare是修改后的代码,对从文件中得到的值求和。

def main():
    file='mbox.txt'
    handle=open(file)
    count=0
    numeri=''
    my_sum = 0;
    count =0
    for line in handle:
        if line.startswith('X-DSPAM-Confidence:'):
            count=count+1
            numeri = line[20:]
            num='%g'%float(numeri.strip(' \n '))
            print float(num)
            my_sum = my_sum + float(num)

    print('Le stringhe che iniziano con "X-DSPAM-Confidence:" sono' ,count)
    print my_sum 

if __name__ == '__main__':
    main()

我假设该文件包含以下内容(因为您没有发布其内容):

X-DSPAM-Confidence: 1
X-DSPAM-Confidence: 2
X-DSPAM-Confidence: 3
X-DSPAM-Confidence: 4 
X-DSPAM-Confidence: 5

输出如下:

1.0
2.0
3.0
4.0
5.0
('Le stringhe che iniziano con "X-DSPAM-Confidence:" sono' ,5)
15.0

最后一个数字是所有数字的总和

【讨论】:

  • 我在文件中有这样的数字:0.8765 0.7644 所以我不得不在浮点数中更改它。
  • 您能解释一下为什么您首先将numeri 转换为带有float(numeri.strip(' \n ')) 的浮点数,然后再转换为带有num='%g'%float(numeri.strip(' \n ')) 的字符串,然后在sum = sum + float(num) 中再次转换为浮点数吗?我看不出有什么原因,但我可能忽略了一些东西。覆盖内置的sum 并不是最好的主意。
猜你喜欢
  • 2022-11-21
  • 2022-11-10
  • 2022-12-04
  • 1970-01-01
  • 2023-01-15
  • 2023-03-15
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多