如何从文本文件中划分数字?
How to divide numbers from a text file?
这是我的文件文本:
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()
有人知道如何解决这个问题吗?
您可以执行以下操作:
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
try:
result = float(t[-1]) / float(t[-2])
print(result)
except ValueError:
pass
当时您不知道要除的值是否是数值,因此用 try-catch 包围操作应该可以解决您的问题。
如果你想变得更"clean",你可以这样做:
def is_float(value):
try:
float(value)
except ValueError:
return False
return True
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
if is_float(t[-1]) and is_float(t[-2]):
result = float(t[-1]) / float(t[-2])
print(result)
然而,想法是一样的。
文件中的 header 行是 Covid-19 Data
。这是第一行,当您调用 t=i.split() 时,您会得到一个包含数据 ['Covid-19', 'Data']
的列表 t
你不能把它们转换成浮点数,因为它们里面有字母。相反,您应该在循环之前阅读前 2 header 行并且不对它们执行任何操作。但是,您将遇到乔治亚州的问题,因为 "NA" 也无法转换为浮点数。
另外几点,捕获所有异常不是好的做法。此外,如果您使用 with 语句打开文件,则无需显式关闭文件。
我使用了您在示例中附加的相同文件。我创建了这个函数,希望它能有所帮助:
with open("test.txt","r") as reader:
lines = reader.readlines()
for line in lines[2:]:
line = line.replace(".","") # Remove points to have the full value
country, number_infections, number_deaths = line.strip().split()
try:
number_infections = float(number_infections)
number_deaths = float(number_deaths)
except Exception as e:
print(f"[WARNING] Could not convert Number of Infections {number_infections} or Number of Deaths {number_deaths} to float for Country: {country}\n")
continue
ratio = number_deaths/number_infections
print(f"Country: {country} D/I ratio: {ratio}")
如您所见,我使用 lines[2:]
避免了文件的 headers,这意味着我将从文件的第 3 行开始。此外,添加了 try/exception 逻辑以避免 non-float 转换。希望这对您有所帮助!
编辑
刚刚注意到千位的格式与“。”一起使用。而不是 "," 在这种情况下,句点在 line 7
.
中被删除
这次执行的结果是:
Country: USA D/I ratio: 0.017980636237897647
Country: Netherlands D/I ratio: 0.07095527332965212
[WARNING] Could not convert Number of Infections 90.0 or Number of Deaths NA to float for Country: Georgia
Country: Germany D/I ratio: 0.007811561110443456
修复了以下内容:
- 您 text-file 中的前两行是 headers。这些需要跳过
- 'NA'无法转换为零
- 如果你的数据中有一个 0,你的程序就会崩溃。现在不会了。
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:
#Skipping headers
next(file)
next(file)
try:
for i in file:
t = i.split()
#Make sure your code keeps working when one of the numbers is zero
x = 0
y = 0
#There are some NA's in your file. Strings not representing
#a number can't be converted to float
if t[1] != "NA":
x = t[1]
if t[2] != "NA":
y = t[2]
if x == 0 or y == 0:
result = 0
else:
result=float(x)/float(y)
print(t[0] + ": " + str(result))
except:
print("fail")
file.close()
输出:
USA: 55.615384615384606
Netherlands: 0.014093385214007782
Georgia: 0
Germany: 0.12801538461538461
这是我的文件文本:
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()
有人知道如何解决这个问题吗?
您可以执行以下操作:
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
try:
result = float(t[-1]) / float(t[-2])
print(result)
except ValueError:
pass
当时您不知道要除的值是否是数值,因此用 try-catch 包围操作应该可以解决您的问题。
如果你想变得更"clean",你可以这样做:
def is_float(value):
try:
float(value)
except ValueError:
return False
return True
with open("myfile.txt", "r") as file:
for i in file:
t = i.split()
if is_float(t[-1]) and is_float(t[-2]):
result = float(t[-1]) / float(t[-2])
print(result)
然而,想法是一样的。
文件中的 header 行是 Covid-19 Data
。这是第一行,当您调用 t=i.split() 时,您会得到一个包含数据 ['Covid-19', 'Data']
你不能把它们转换成浮点数,因为它们里面有字母。相反,您应该在循环之前阅读前 2 header 行并且不对它们执行任何操作。但是,您将遇到乔治亚州的问题,因为 "NA" 也无法转换为浮点数。
另外几点,捕获所有异常不是好的做法。此外,如果您使用 with 语句打开文件,则无需显式关闭文件。
我使用了您在示例中附加的相同文件。我创建了这个函数,希望它能有所帮助:
with open("test.txt","r") as reader:
lines = reader.readlines()
for line in lines[2:]:
line = line.replace(".","") # Remove points to have the full value
country, number_infections, number_deaths = line.strip().split()
try:
number_infections = float(number_infections)
number_deaths = float(number_deaths)
except Exception as e:
print(f"[WARNING] Could not convert Number of Infections {number_infections} or Number of Deaths {number_deaths} to float for Country: {country}\n")
continue
ratio = number_deaths/number_infections
print(f"Country: {country} D/I ratio: {ratio}")
如您所见,我使用 lines[2:]
避免了文件的 headers,这意味着我将从文件的第 3 行开始。此外,添加了 try/exception 逻辑以避免 non-float 转换。希望这对您有所帮助!
编辑
刚刚注意到千位的格式与“。”一起使用。而不是 "," 在这种情况下,句点在 line 7
.
这次执行的结果是:
Country: USA D/I ratio: 0.017980636237897647
Country: Netherlands D/I ratio: 0.07095527332965212
[WARNING] Could not convert Number of Infections 90.0 or Number of Deaths NA to float for Country: Georgia
Country: Germany D/I ratio: 0.007811561110443456
修复了以下内容:
- 您 text-file 中的前两行是 headers。这些需要跳过
- 'NA'无法转换为零
- 如果你的数据中有一个 0,你的程序就会崩溃。现在不会了。
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:
#Skipping headers
next(file)
next(file)
try:
for i in file:
t = i.split()
#Make sure your code keeps working when one of the numbers is zero
x = 0
y = 0
#There are some NA's in your file. Strings not representing
#a number can't be converted to float
if t[1] != "NA":
x = t[1]
if t[2] != "NA":
y = t[2]
if x == 0 or y == 0:
result = 0
else:
result=float(x)/float(y)
print(t[0] + ": " + str(result))
except:
print("fail")
file.close()
输出:
USA: 55.615384615384606
Netherlands: 0.014093385214007782
Georgia: 0
Germany: 0.12801538461538461