按照要求实现如下要求效果
4.假如现在有个文本,格式如下:
a  1
b  3
c  2
d  7
b  5
a  3 
g  2
f  6
d  9
即左边是随机字母,右边是随机数字,要求写个脚本使其输出格式为:
a  4
b  8
c  2
d  16
f  6
g  2
即将相同的字母后面的数字加在一起,按字母的顺序输出。
  1. [root@LAMP-2 ~]# cat 98.txt
    a  1
    b  3
    c  2
    d  7
    b  5
    a  3 
    g  2
    f  6
    d  9
    [root@LAMP-2 ~]# awk '{if(!a[$1]) b[++t]=$1;a[$1]+=$2;}END{for(i=1;i<=t;i++) print b[i],a[b[i]]}' 98.txt |sort
    a 4
    b 8
    c 2
    d 16
    f 6
    g 2
    [root@LAMP-2 ~]# awk '{a[$1]+=$2;}END{for(i in a){{print i" "a[i];}}}' 98.txt
    a 4
    b 8
    c 2
    d 16
    f 6
    g 2
    [root@LAMP-2 ~]#
  2. 用python的方法
[root@LAMP-2 ~]# cat 98.txt 
a  1
b  3
c  2
d  7
b  5
a  3 
g  2
f  6
d  9
[root@LAMP-2 ~]# cat 98.py 
with open('./98.txt','rt') as f:
        dic={}
        for line in f.readlines():
                a,b=line.split()
                if a in dic.keys():
                        dic[a] +=int(b)
                else:
                        dic.update({a:int(b)})
        for key,val in dic.items():
                print(key,val)
[root@LAMP-2 ~]# 
posted on 2015-12-30 14:05  牧羊伯爵  阅读(305)  评论(0编辑  收藏  举报