Python新手在这里。我一直在努力通过这段代码基本上创建一个包含日期的字符串。我有一些代码工作来获取我想要的数据,但是我需要帮助格式化字符串以将数据绑定在一起。
这是我到目前为止所做的:
def get_rectype_count(filename, rectype):
return int(subprocess.check_output('''zcat %s | '''
'''awk 'BEGIN {FS=";"};{print $6}' | '''
'''grep -i %r | wc -l''' %
(filename, rectype), shell=True))
str = "MY VALUES ("
rectypes = 'click', 'bounce'
for myfilename in glob.iglob('*.gz'):
#print (rectypes)
print str.join(rectypes)
print (timestr)
print([get_rectype_count(myfilename, rectype)
for rectype in rectypes])
我的输出如下:
clickMY VALUES (bounce
'2015-07-01'
[222, 0]
我正在尝试创建此输出文件:
MY VALUES ('2015-07-01', click, 222)
MY VALUES ('2015-07-01', bounce, 0)
答案 0 :(得分:5)
当你在一个字符串上调用join时,joins together everything in the sequence传递给它,使用它自己作为分隔符。
>>> '123'.join(['click', 'bounce'])
click123bounce
Python支持使用replacement fields格式化字符串:
>>> values = "MY VALUES ('{date}', {rec}, {rec_count})"
>>> values.format(date='2015-07-01', rec='click', rec_count=222)
"MY VALUES ('2015-07-01', click, 222)"
使用您的代码:
for myfilename in glob.iglob('*.gz'):
for rec in rectypes:
rec_count = get_rectype_count(myfilename, rec)
print values.format(date=timestr, rec=rec, rec_count=rec_count)
编辑:
如果您想使用join
,可以加入换行符\n
:
>>> print '\n'.join(['line1', 'line2'])
line1
line2
把它放在一起:
print '\n'.join(values.format(date=timestr,
rec=rec,
rec_count=get_rectype_count(filename, rec))
for filename in glob.iglob('*.gz')
for rec in rectypes)
答案 1 :(得分:2)
试试这个:
str1 = "MY VALUES ("
rectypes = ['click', 'bounce']
K=[]
for myfilename in glob.iglob('*.gz'):
#print (rectypes)
#print str.join(rectypes)
#print (timestr)
k=([get_rectype_count(myfilename, rectype)
for rectype in rectypes])
for i in range(0,len(rectypes)):
print str1+str(timestr)+","+rectypes[i]+","+str(k[i])+")"