recherche

Maison  >  Questions et réponses  >  le corps du texte

python处理txt文件

我现在有个txt文件的格式如下:
167

19 167

167

21 147

175 21 147

175 16 108

175 123 16 108

175 123 10 108

36 123

我现在想用python将其每行的各个数相加,得到每一行都有一个和,结果应该是这样:
167
186
167
168
我需要这样的结果,但是现在发现问题在于每行的列数是不固定的,就不知道怎么得出这样的结果了。orz

阿神阿神2889 Il y a quelques jours504

répondre à tous(2)je répondrai

  • ringa_lee

    ringa_lee2017-04-17 17:35:08

    # coding:utf-8
    
    # 每行求和
    def addEachLine(line):
        values = line.split()
        values = [int(v) for v in values if v.strip()]
        return sum(values)
    
    
    def main():
        result = []
        with open("input.txt") as f:
            buf = f.read()
            lines = buf.splitlines()
            lines = [l for l in lines if l.strip()]
            # 对拆分的每一行进行计算
            for l in lines:
                result.append(addEachLine(l))
        # 打印结果
        for r in result:
            print r
    
    if __name__ == '__main__':
        main()
    

    Sortie
    167
    186
    167
    168
    343
    299
    422
    416
    159

    répondre
    0
  • 迷茫

    迷茫2017-04-17 17:35:08

    Lire chaque ligne de données sous forme de chaîne telle que str=

    str='175 123 10 108'
    # 通过切割拆分并转换为int的-》 [175, 123, 10, 108]
    arr= map(int,str.split(' '))
    # 对int列表求和-》416
    sum(arr)

    répondre
    0
  • Annulerrépondre