给定字符串中精确字符串的计数,update conu

2024-04-16 08:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取给定字符串中某个精确字符串的计数,然后在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循环生成母版.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是第一行/标题。你知道吗

到目前为止还不错。我需要更新中的值母版.csv从我的弦数。所以每次找到518,它就增加1。你知道吗

如果我有这个作为我的示例字符串:“100;100;100;5 16;”。我的预期产出将是:

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

Tags: 文件csv字符串in示例forrange数字
1条回答
网友
1楼 · 发布于 2024-04-16 08:31:04

使用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

生成母版.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

相关问题 更多 >