这里是 Python 新手。我一直在研究这段代码,基本上是创建一个包含日期的字符串。我有一些代码可以获取我想要的数据,但是我需要帮助格式化为字符串以将数据绑定(bind)在一起。
这是我目前所拥有的:
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)
请您参考如下方法:
当你在一个字符串上调用 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)
