1

I have a script which exports some results to a dbf file (dbf is my only export option for the software I am using). I would like to use these results (number of rows will vary) to output a sentence containing the results to a file.

For example

Cars.dbf

Toyota
Mazda
Kia
Volkswagon

I want to output the following sentence:

Within this neighborhood there is a Toyota, Mazda, Kia, and Volkswagon parked on the street.

If the results are two I do not want commas:

Cars.dbf

Toyota
Mazda

Within this neighborhood there is a Toyota and Mazda parked on the street.

Cars.dbf

empty

There are no cars parked on the street within this neighborhood.

I know how to do if else statements, but am unsure how to pass the dbf records as variables in a sentence. Ideas anyone?

Using python 2.7.

A thousand thanks in advance.

4

1 に答える 1

0

私の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すべての名前が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ます。そしてもちろん、最後の項目の直前に「and」が必要です。車が 4 台ある場合は、次のようになります。cars%s

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%

于 2013-02-22T22:08:53.090 に答える