如何合并相似字符串的数值?

时间:2019-05-30 15:48:10

标签: python python-3.x

我有一个许可证列表和相关的许可证计数,例如:

1 Third Party SIP Device Seat   
1 Third Party SIP Device Seat   
1 Third Party SIP Device Seat   
3 Station   
3 Station   
3 Station   
20 Station

列表永远不会以相同的顺序排列,我只需要添加每种许可证类型的总数,因此在示例中,我需要返回:

3 Third Party SIP Device Seat
29 Station

数据被输入到未保存的记事本中,然后移入数据库中。使用excel不适用于数字和名称之间的空格,而不是制表符。

完成此任务的最简单方法是什么?

3 个答案:

答案 0 :(得分:2)

这是一个非常丑陋的解决方案:

from functools import reduce
from collections import defaultdict

lines = [       # replace with e.g: with open('input.txt', 'r') as f: lines = f.readlines()
  "1 Third Party SIP Device Seat",   
  "1 Third Party SIP Device Seat",  
  "1 Third Party SIP Device Seat", 
  "3 Station",
  "3 Station",  
  "3 Station",  
  "20 Station"
]

def f(acc, x):
  acc[" ".join(x.split(" ")[1:])] += int(x.split(" ")[0]) # first element is the count, everything after we use as "key"
  return acc

r = dict(reduce(f, lines, defaultdict(int)))

print(r)
# {'Third Party SIP Device Seat': 3, 'Station': 29}

# to write to file:
with open("output.txt", "w") as f:  
  for k, v in r.items():
    f.write(str(v) + " " + str(k))

答案 1 :(得分:1)

您想要一个分组依据。幸运的是itertools有一个

from itertools import groupby 

text = """1 Third Party SIP Device Seat    
1 Third Party SIP Device Seat    
1 Third Party SIP Device Seat    
3 Station    
3 Station    
3 Station    
0 Station""" 

# clean stuff up and split on first space
lines = [line.strip().split(" ", 1) for line in text.split("\n")]

# groupby
result = []
for k, g in groupby(lines, lambda x: x[1]): 
    total = 0 
    for i in g: 
        total += int(i[0]) 
    result.append([k, total])  
print(result)

答案 2 :(得分:1)

在名为“ licences.txt”的“已保存记事本文件”中存储数据的完整解决方案:

from collections import Counter
counter=Counter()
with open ('licences.txt','r') as f:
    for line in f:
        count,*words = line.split()
        counter[" ".join(words)] += int(count)

with open('grouped_licences.txt','w') as f:
    for licence,total in counter.items():
        f.write(str(total) + " " + licence + "\n")        

然后结果在文件grouped_licences.txt中:

    3 Third Party SIP Device Seat 
    29 Station

使用pandas的另一种解决方案:

df=pandas.read_csv('licences.txt', sep=" ",header=None).fillna("")        
df["licence"]=df.iloc[:,1:].apply(" ".join,axis=1)        
print(df.groupby("licence")[0].sum())        

对于:

licence
Station                           29
Third Party SIP Device Seat        3