python爬虫 python处理txt文件

来源:互联网  时间:2016/6/20 11:58:03

关于网友提出的“python爬虫 python处理txt文件”问题疑问,本网通过在网上对“python爬虫 python处理txt文件”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题:python爬虫 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


解决方案1:

读出每行数据是一个字符串如 str=

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

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

输出
167
186
167
168
343
299
422
416
159

上一篇python 有好的文本分类库吗?
下一篇(python)用phantomjs时超时报错,用谷歌浏览器没有问题,这是什么原因
明星图片
相关文章
《python爬虫 python处理txt文件》由码蚁之家搜集整理于网络,
联系邮箱:mxgf168#qq.com(#改为@)