【问题标题】:How do I read certain 4 digits in a file and move to another line and do the same and so on如何读取文件中的某些 4 位数字并移动到另一行并执行相同操作等等
【发布时间】:2019-10-14 04:48:52
【问题描述】:

所以我有这个问题需要解决。我有一个类似的文件:

11-08-2012;1485;10184;7,53;31;706;227;29;6;1102

12-08-2012;2531;10272;7,59;25;695;222;26;22;1234

13-08-2012;1800;13418;8,66;46;714;203;50;6;0757

14-08-2012;2009;11237;9,43;81;655;246;49;7;1783

我应该能够读取“1485”,然后是“2531”部分,然后是“1800”部分,一直到文件末尾,最后总结它们。我怎么做?我在这篇文章下写了我是如何尝试用 while 来解决这个问题的。但我似乎迷失了这个。有人可以帮忙吗?

当真时:

    f.seek(12)
    text=f.read(4)

    text=f.readline()
    if(text==""):
        break
    return text

【问题讨论】:

    标签: python line readline readlines


    【解决方案1】:

    有很多方法可以做到这一点,numpypandas、简单的coroutines 等等。我正在添加最接近您的方法的一个。

    total = 0
    with open('exmplefile.txt','r') as f:
        for line in f:
            elements = line.split(';')
            num_of_interest = int(elements[1])
            # you can add a print if you want
            total += num_of_interest
    print(total)
    

    【讨论】:

      【解决方案2】:

      此解决方案是通过获取常用术语的第一个和第二个索引,在本例中为 ;

      with open(filename,'r') as file:
          file_list = file.readlines()
      
      sum = 0
      
      for line in file_list:
          loc = line.find(';')
          first_loc = loc + 1
          last_loc = loc +line[loc+1:].find(';')+1
      
          sum = sum + int(line[first_loc:last_loc])
      
      print(sum)
      

      【讨论】:

        【解决方案3】:

        试试这个

        mylist = []
        for string in file:
            mynum = string.split(';')[1]
            mylist.append(mynum)
        sum([int(i) for i in mylist])
        

        【讨论】:

          【解决方案4】:

          此解决方案适用于当 4 位不是数组中的第二项时

          with open("path/to/file") as f:
            f1 = f.readlines()
          
            sum = 0
            for line in f1:
              lineInArray = line.split(';')
              for digit in lineInArray:
                if len(digit.strip()) == 4 and digit.strip().isnumeric():
                  sum += int(digit)
          

          【讨论】:

          • Cosman,with 语法是一个上下文管理器,可确保在打开文件以处理其内容后关闭文件。对于代码中的 with line 语句,您可以替换为 f = open('path/to/file') 并取消缩进该块。但是,使用这种样式,您必须在代码末尾调用f.close()
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-02-12
          • 1970-01-01
          • 2013-05-28
          • 2021-10-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多