Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从文本文件中分割数字?_Python_Text Files_Division - Fatal编程技术网

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

Python 如何从文本文件中分割数字?,python,text-files,division,Python,Text Files,Division,这是我的文件文本: 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.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()

有人知道如何解决这个问题吗

您可以执行以下操作:

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
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)
此时,您不知道您试图分割的值是否为数值,因此,使用try-catch围绕操作应该可以解决您的问题

如果您想变得更干净,可以执行以下操作:

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
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)

不过,想法是一样的。

您可以执行以下操作:

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
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)
此时,您不知道您试图分割的值是否为数值,因此,使用try-catch围绕操作应该可以解决您的问题

如果您想变得更干净,可以执行以下操作:

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
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)

然而,想法是相同的。

文件中的标题行是新冠病毒-19数据。这是第一行,当您调用t=i.split时,您将得到一个列表t,其中包含数据['Covid-19','data']

您无法将其转换为浮点数,因为其中包含字母。相反,您应该阅读循环之前的前2行标题,并且不处理它们。然而,你会遇到格鲁吉亚的问题,因为NA也不能转换为浮动


还有几点,有一个全面的例外不是好的做法。另外,如果使用with语句打开文件,则不需要显式关闭文件。

文件中的头行是Covid-19数据。这是第一行,当您调用t=i.split时,您将得到一个列表t,其中包含数据['Covid-19','data']

您无法将其转换为浮点数,因为其中包含字母。相反,您应该阅读循环之前的前2行标题,并且不处理它们。然而,你会遇到格鲁吉亚的问题,因为NA也不能转换为浮动


还有几点,有一个全面的例外不是好的做法。另外,如果使用with语句打开文件,则不需要显式关闭文件。

我使用的文件与您在示例中附加的文件相同。我创建了这个函数,希望它能帮助:

使用opentest.txt,r作为读卡器: lines=reader.readlines 对于行中的行[2:]: line=line.replace.,删除点以获得完整值 国家,感染人数,死亡人数=line.strip.split 尝试: 感染人数=感染人数 死亡人数=死亡人数 例外情况除外,如e: printf[警告]无法将感染数{Number_infectures}或死亡数{Number_defectures}转换为浮动的国家:{Country}\n 持续 比率=死亡人数/感染人数 printfCountry:{country}D/I比率:{ratio} 如您所见,我使用第[2:]行避免了文件的标题,这意味着我将从文件的第3行开始。此外,还添加了try/exception逻辑以避免非浮点转换。希望这有帮助

编辑 刚刚注意到数千的格式是与一起使用的。相反,在这种情况下,第7行中删除了该期间

此执行的结果是:

国家:美国D/I比率:0.017980636237897647 国家:荷兰D/I比率:0.07095527332965212 [警告]无法将国家:格鲁吉亚的感染人数或死亡人数转换为90.0 国家:德国D/I比率:0.00781156111044456
我使用了您在示例中附加的相同文件。我创建了这个函数,希望它能帮助:

使用opentest.txt,r作为读卡器: lines=reader.readlines 对于行中的行[2:]: line=line.replace.,删除点以获得完整值 国家,感染人数,死亡人数=line.strip.split 尝试: 感染人数=感染人数 死亡人数=死亡人数 例外情况除外,如e: printf[警告]无法将感染数{Number_infectures}或死亡数{Number_defectures}转换为浮动的国家:{Country}\n 持续 比率=死亡人数/感染人数 printfCountry:{country}D/I比率:{ratio} 如您所见,我使用第[2:]行避免了文件的标题,这意味着我将从文件的第3行开始。此外,还添加了try/exception逻辑以避免非浮点转换。希望这有帮助

编辑 刚刚注意到数千的格式是与一起使用的。相反,在这种情况下,第7行中删除了该期间

此执行的结果是:

国家:美国D/I比率:0.017980636237897647 国家:荷兰D/I比率:0.07095527332965212 [警告]无法将国家:格鲁吉亚的感染人数或死亡人数转换为90.0 国家:德国D/I比率:0.00781156111044456 修复了以下问题:

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
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)
文本文件的前两行是标题。这些需要跳过 “NA”不能转换为零 如果数据中有0,则程序将崩溃。 现在不会了。 输出:

USA: 55.615384615384606
Netherlands: 0.014093385214007782
Georgia: 0
Germany: 0.12801538461538461
修复了以下问题:

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
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)
文本文件的前两行是标题。这些需要跳过 “NA”不能转换为零 如果数据中有0,则程序将崩溃。现在不会了。 输出:

USA: 55.615384615384606
Netherlands: 0.014093385214007782
Georgia: 0
Germany: 0.12801538461538461

也许它只是阻塞了文件的第一行,其中包含列名字符串?试着把这一行从循环中去掉。这是一种很难解析的文件格式。有时它有全部3个数据点,有时没有。它由空格分隔,但是名称中有空格的国家呢?也许最好的答案是获得更好的数据集!像csv一样。约翰·霍普金斯大学每天都在更新github上的数据。还有其他的来源。你还坚持使用这种文件格式吗?我注意到在您的示例中,您自己生成了它。如果不使用分隔符,会容易得多。也许它只是阻塞了文件的第一行,其中包含列名字符串?试着把这一行从循环中去掉。这是一种很难解析的文件格式。有时它有全部3个数据点,有时没有。它由空格分隔,但是名称中有空格的国家呢?也许最好的答案是获得更好的数据集!像csv一样。约翰·霍普金斯大学每天都在更新github上的数据。还有其他的来源。你还坚持使用这种文件格式吗?我注意到在您的示例中,您自己生成了它。如果没有分隔符,那就容易多了。我不同意在输出中显示乔治亚州的结果,因为这将意味着根据你的比例,所有感染者都将死亡。此外,我认为用户提供的输入需要重新格式化为124.356,将等于124356,删除句点。@EnriqueBet True。编辑。更好是的,看起来好多了我不同意在输出中显示佐治亚州的结果,因为根据你的比例,这将意味着所有感染者都将死亡。此外,我认为用户提供的输入需要重新格式化为124.356,将等于124356,删除句点。@EnriqueBet True。编辑。更好是的,看起来好多了D