Domanda

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.

È stato utile?

Soluzione

Using my dbf package:

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

After the for record in table loop all the names are in the cars list. At that point it is simple string substitution:

# 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+

The middle = line is getting a little fancy with string substitution. Each %s will be replaced by an entry from cars, and if you have to have the same number of items in cars as you have %s's. And of course you want an 'and' just before the last item. So if you have four cars:

cars = ['Mazda', 'Ford', 'Dodge', 'Yugo']

then

len(cars) - 1 == 3

so

'%s, ' * (len(cars)-1) == '%s, %s, %s, '

and then we add the last part

'%s, ' * (len(cars)-1) + 'and a %s' == '%s, %s, %s, and a %s'

finally, the % string substitute function sees

'%s, %s, %s, and a %s' % tuple(cars)

which would give us

 'Mazda, Ford, Dodge, and a Yugo'

Note: we had to say tuple(cars) because cars was a list and % needs either a single item or a tuple of items.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top