如何从文本文件中分割数字?

问题描述 投票:1回答:3

这是我的文件文本:

Covid-19 Data
Country / Number of infections / Number of Death
USA  124.356  2.236
Netherlands  10.866  771
Georgia  90  NA
Germany  58.247  455

我创建了一个函数来计算与感染相比的死亡率,但是它不起作用,因为某些值不是浮动的。

f=open("myfile.txt","w+")

x="USA" + " " + " " + "124.356" + " " + " " + "2.236"
y="Netherlands" + " " + " " + "10.866" + " " + " " + "771"
z="Georgia" + " " + " " + "90" + " " + " " + "NA"
w="Germany" + " " + " " + "58.247" + " " + " " + "455"

f.write("Covid-19 Data" + "\n" + "Country" + " " + "/" + " " + "Number of infections" + " "  + "/" + " " + "Number of Death" + "\n")
f.write(x + "\n")
f.write(y + "\n")
f.write(z + "\n")
f.write(w)

f.close()

with open("myfile.txt", "r") as file:


        try:
            for i in file:
                t = i.split()
                    result=float(t[-1])/float(t[-2])
                    print(results)
        except:
            print("fail")
        file.close()

有人知道如何解决此问题吗?

python text-files division
3个回答
3
投票
您可以执行以下操作:

0
投票
您在文件中的标题行是Covid-19 Data。这是第一行,当您调用t = i.split()时,您将看到一个列表t,其中包含数据['Covid-19', 'Data']

0
投票
我使用了您在示例中附加的相同文件。我希望创建此函数对您有帮助:
© www.soinside.com 2019 - 2024. All rights reserved.