【问题标题】:Python txt files, average, informationPython txt 文件,平均,信息
【发布时间】:2014-04-21 00:22:11
【问题描述】:

我有一个包含这个的 .txt 文件(应该是随机名称):

My Name 4 8 7 
Your Name 5 8 7 
You U 5 9 7
My My 4 8 5
Y Y 8 7 9 

我需要将信息放入带有名称+数字平均值的文本文件 results.txt 中。我该怎么做?

with open(r'stuff.txt') as f:
    mylist = list(f)

i = 0
sk = len(mylist)
while i < sk - 4:
    print(mylist[i], mylist[i+1], mylist[i+2], mylist[i+3])
    i = i + 3

【问题讨论】:

    标签: python file text average


    【解决方案1】:

    首先,打开输入和输出文件:

    with open("stuff.txt") as in_file:
        with open("results.txt", "w") as out_file:
    

    由于问题只需要在每一行上独立处理,每个line 的简单循环就足够了:

            for line in in_file:
    

    将空格处的每一行拆分为字符串列表 (row):

                row = line.split()
    

    数字出现在前两个字段之后:

                str_nums = row[2:]
    

    但是,这些仍然是字符串,因此必须将它们转换为浮点数才能对其执行算术运算。这会产生一个浮动列表 (nums):

                nums = map(float, str_nums)
    

    现在计算平均值:

                avg = sum(nums) / len(str_nums)
    

    最后,将名称和平均值写入输出文件。

                out_file.write("{} {} {}\n".format(row[0], row[1], avg))
    

    【讨论】:

      【解决方案2】:

      这个呢?

      with open(fname) as f:
         new_lines = []
         lines = f.readlines()       
         for each in lines:          
           col = each.split()
           l = len(col)#<-- length of each line
           average = (int(col[l-1])+int(col[l-2])+int(col[l-3]))/3
           new_lines.append(col[0]+col[1]+str(average) + '\n')
         for each in new_lines:#rewriting new lines into file 
           f.write(each)
         f.close()
      

      【讨论】:

      • 为什么平均不能是average = (int(col[2])+int(col[3])+int(col[4]))/3?为什么我们需要一条线的长度?老实说,我正在学习 Python。
      • @AndyG,我倒退了,因为所有 3 个数字都是该行中的最后 3 个项目。我确保我真的拿了 3 个数字。如果该行突然变成A B C D 12 23 3,那么col[3] 将是一个字符串.. 这有意义吗?
      • 这是有道理的。在这种情况下,您不想要len(col) 而不是len(each) 吗?
      • 不,col 是行中的每个项目。我需要行长,据此,我会推断出最后 3 行.. 你怎么看
      • 但是len(each) 返回整个字符串的长度(不是列数),它可能超过列中的索引数,所以col[l-1] 会超出范围。我用 OP 的例子测试了这段代码。附带说明一下,您可能希望在 new_lines 中附加的字符串之间有空格
      【解决方案3】:

      我试过了,效果不错:

      inputtxt=open("stuff.txt", "r")
      outputtxt=open("output.txt", "w")
      output=""""""
      for i in inputtxt.readlines():
          nums=[]
          name=""
          for k in i:
              try:
                  nums.append(int(k))
              except:
                  if k!=" ":
                      name+=k
          avrg=0
          for j in nums:
              avrg+=j
          avrg/=len(nums)
          line=name+" "+str(avrg)+"\n"
          output+=line
      outputtxt.write(output)
      inputtxt.close()
      outputtxt.close()
      

      【讨论】:

      • 它确实删除了名称中的空格
      猜你喜欢
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 2021-11-22
      • 2016-01-21
      相关资源
      最近更新 更多