【问题标题】:Summing columns in a text file对文本文件中的列求和
【发布时间】:2015-11-06 17:26:18
【问题描述】:

我有一个如下所示的数据文件:

 TOPIC:topic_0 2056
 ab  2.0
 cd  5.0
 ef  3.0
 gh  10.0

 TOPIC:topic_1 1000
 aa  3.0
 bd  5.0
 gh  2.0

等等……直到 TOPIC:topic_2000。第一行是主题和权重。也就是说,我有该特定主题中的单词及其各自的权重。

现在,我想总结每个主题的第二列并检查它给出的价值。也就是说,我想得到如下输出:

 Topic:topic_0  20
 Topic:topic_1  10

即主题号与列值之和(即主题1中,词的权重为2,5,3,10)。我尝试使用:

with open('Input.txt') as in_file:
    for line in in_file:
        columns = line.split(' ')
        value = columns[0]

        if value[:6] == 'TOPIC:':
            total_value = columns[1]
            total_value = total_value[:-1]
            total_values = float(total_value)
            #print '\n'
            print columns[0]

但是,我不知道如何从这个开始。这只是打印主题编号。请帮忙!

【问题讨论】:

    标签: python linux python-2.7


    【解决方案1】:
    import re
    
    input = """
    TOPIC:topic_0 2056
     ab  2.0
     cd  5.0
     ef  3.0
     gh  10.0
    
     TOPIC:topic_1 1000
     aa  3.0
     bd  5.0
     gh  2.0
    """
    
    result = {}
    for line in input.splitlines():
        line = line.strip()
        if not line:
            continue
    
        columns = re.split(r"\s+", line)
        value = columns[0]
        if value[:6] == 'TOPIC:':
            result[value] = []
            points = result[value]
            continue
    
        points.append(float(columns[1]))
    
    for k, v in result.items():
        print k, sum(v)
    

    【讨论】:

    • 我的输入文件有 2000 个这样的主题。我可以加载输入文件并对其执行相同的代码吗?
    • 只需将input.splitlines() 替换为您的原始代码。这取决于您的数据大小,考虑到现在的千兆字节内存,2000 对我来说并不是一个大数字。
    • 当我将 open('assigned0_lda01_100.txt','r') 用作 f: f1 = f.read() 时,它给了我一个错误“列表对象没有属性拆分”。 split() result = {} for line in f1.split(): line1 = line.strip()
    • read() 返回整个文件内容...您的原始代码很好。 with open('Input.txt') as f: for line in f: ...
    【解决方案2】:

    试试这个:适用于 Python 2.7 和 3.5

    import re;
    
    total = 0
    temp = ''
    topic = {}
    p = re.compile('[a-z]*')
    
    with open('Input.txt') as in_file:
        for line in in_file:
            line = line.strip()
            if not line: continue
    
            if line.startswith('TOPIC:'):
                temp = (line.split(' ')[0]).replace('TOPIC:', '')
                topic[temp] = 0;
            else:
                value = p.sub('', line).strip()
                topic[temp] = float(topic[temp]) + float(value)
    
    for key in topic:
        print ("Topic:%s %s" % (key, topic[key]))
    

    结果:

    $ /c/Python27/python.exe input.py
    Topic:topic_1 10.0
    Topic:topic_0 20.0
    

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多