[英]Pass dbf data to sentence and save as text file using Python 2.7
我有一个脚本,可以将一些结果导出到dbf文件(dbf是我正在使用的软件的唯一导出选项)。 我想使用这些结果(行数会有所不同)将包含结果的句子输出到文件中。
例如
Cars.dbf
Toyota
Mazda
Kia
Volkswagon
我想输出以下句子:
在这附近,街道上停着一辆丰田,马自达,起亚和大众汽车。
如果结果为两个,我不要逗号:
Cars.dbf
Toyota
Mazda
在附近,这条街上停着一辆丰田和马自达。
Cars.dbf
empty
该社区内的街道上没有停车场。
我知道if else语句怎么办,但不确定如何将dbf记录作为变量传递给句子。 有任何想法吗?
使用python 2.7。
一千个感谢。
使用我的dbf软件包 :
import dbf
table = dbf.Table('Cars', default_data_types={'C':dbf.Char}) # don't want extra spaces
cars = []
table.open()
for record in table:
cars.append(record[0]) # or cars.append(record.make) if 'make' is the field name
if len(cars) == 1 and cars[0] == 'empty'):
# print no cars sentence
elif len(cars) == 1:
# print one car sentence
elif len(cars) == 2:
# print two car sentence
else:
# print many car sentence
for record in table
的for record in table
循环之后,所有名称都在cars
列表中。 在这一点上,是简单的字符串替换:
# many car case
first = "Within this neighborhood there is a "
last = " parked on the street."
middle = ('%s, ' * (len(cars)-1) + 'and a %s') % tuple(cars)
print first + middle + last+
middle =
行通过字符串替换变得有点花哨。 每个%s
都将替换为cars
的一个条目,并且如果您必须拥有与%s
相同数量的cars
项。 当然,您要在最后一项之前加上“和”。 因此,如果您有四辆车:
cars = ['Mazda', 'Ford', 'Dodge', 'Yugo']
然后
len(cars) - 1 == 3
所以
'%s, ' * (len(cars)-1) == '%s, %s, %s, '
然后添加最后一部分
'%s, ' * (len(cars)-1) + 'and a %s' == '%s, %s, %s, and a %s'
最后, %
字符串替代函数看到
'%s, %s, %s, and a %s' % tuple(cars)
这会给我们
'Mazda, Ford, Dodge, and a Yugo'
注意:我们必须说tuple(cars)
因为cars
是一个list
, %
需要一个或一个元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.