【问题标题】:Count of an exact string in a given string, update count给定字符串中精确字符串的计数,更新计数
【发布时间】:2013-04-20 19:15:30
【问题描述】:

我正在尝试获取给定字符串中确切字符串的计数,然后在 csv 文件的行中找到它并更新计数。详细:

我有一个示例字符串如下: “5 18;4 00;4 00;5 16;5 16;5 16;5 15;3 19;3 16;3 16;3 15;3 15;”。

字符串中的第一个数字是日期(1-7,其中 1 是星期一,5 是星期五,等等)。空格后的第二个数字是小时(24 小时。其中 18 是下午 6 点)。每个条目由分号和空格分隔。

我有一个包含天数 (1-7) 和小时数 (00-23) 的主文件。我生成的日期和时间如下:

for day in range(1, 8):
    for hour in range(00, 24):
       # Write day + hour, nums.
       writerCommits.writerow([str(day) + " " + str(hour), "0"]); # to write  csv

上面的for循环生成master.csv:

date, count
1 0,0
1 1,0
1 2,0
1 3,0
1 4,0
...
7 19,0
7 20,0
7 21,0
7 22,0
7 23,0

总共 169 行 = (7 x 24) + 1,其中 1 是第一行/标题。

到目前为止一切顺利。我需要使用我的字符串中的计数更新 master.csv 中的值。因此,每次找到 5 18 时,它都会增加 1。

如果我将其作为示例字符串:“1 00; 1 00; 1 00; 5 16;”。我的预期输出将是:

date, count
1 0,3
...
5 16,1
...
7 23, 0

【问题讨论】:

    标签: python loops csv


    【解决方案1】:

    使用collections.Counter:

    import csv
    from collections import Counter
    
    strs="1 00; 1 00; 1 00; 5 16;"
    c=Counter(tuple(map(int,x.split())) for x in strs.split(";") if x.strip())
    
    #c is Counter({(1, 0): 3, (5, 16): 1})
    #here I used a tuple (day,hour) as key and item after `,` as value
    
    with open('master.csv', 'rb') as f1,open("newfile.csv","w") as f2:
         spamreader = csv.reader(f1, delimiter=',')
         header=next(spamreader)
         f2.write(",".join(header)+'\n')
         for row in spamreader:
             key,val=tuple(map(int,row[0].split())),int(row[1])
             #fetch tuple (day,hour) from the current line
             #val is the value after `,`
    
             val+=c[key] #new value is count from c + count from csv file
    
             f2.write("{0},{1}\n".format(" ".join(map(str,key)),val))
    

    这将创建一个名为 newfile.csv 的新文件,其中现在包含:

    date, count
    1 0,3
    1 1,0
    1 2,0
    1 3,0
    1 4,0
    ...
    7 19,0
    7 20,0
    7 21,0
    7 22,0
    7 23,0
    

    将 master.csv 生成为字符串变量:

    In [69]: strs="date, count\n"
    
    In [70]: for day in xrange(1,8):
        for hour in xrange(24):
            strs+="{0} {1},{2}\n".format(day,hour,"0")  #use string formatting
       ....:         
    
    In [71]: print strs
    date, count
    1 0,0
    1 1,0
    1 2,0
    1 3,0
    ...
    7 21,0
    7 22,0
    7 23,0
    

    【讨论】:

    • 这绝对会创造出接近我想要的东西。非常感谢。还有一个问题:如何将订单保存在我的 csv 文件中?我需要 169 行。
    • 169 行 = 1 00,count1 到 7 23,count2;
    • @Ashwini ... 这行得通。我需要逐步了解您所做的事情。谢谢!!!
    • @chatu 我添加了一些 cmets,以便您了解代码在做什么。
    • 感谢这些 cmets。另一个快速的问题:如果我要清理我的代码并用字符串变量替换主文件 (f1)。我怎样才能做到这一点。我的尝试在这里:template = "date, count"; for day in range(1, 8): for hour in range(00, 24): # 写天 + 小时,计数 (0)。模板=模板+“\n”+str(天)+“”+str(小时)+“,”+“0”; #谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多