Форум сайта python.su
Опять пример из книги по питон3 не заводится
# создаем файл данных инцидентов
# report_id = str max 8
# date = datetime.date
# airport = str непустое, без символов перевода строки
# aircraft_id = str непустое без символов перевода строки
# aircraft_type = str непустое, без символов перевода строки
# pilot_percent_hours_on_type = float в диапазоне от 0.0 до 100.0
# pilot_total_hours = int положительное ненулевое значение
# midair = bool
# narrative = str многострочный текст
import os
import sys
import datetime
import textwrap
class IncidentError(Exception): pass
class IncidentCollection(dict):
def values(self):
for report_id in self.keys():
yield self[report_id]
def items(self):
for report_id in self.keys():
yield (report_id, self[report_id])
def __iter__(self):
for report_id in sorted(super(IncidentCollection, self).keys()):
yield report_id
keys = __iter__
def export_text(self, filename):
wrapper = textwrap.TextWrapper(initial_indent=" ",
subsequent_indent=" ")
fh = None
try:
fh = open(filename, "w")
for incident in self.values():
narrative = "\n".join(wrapper.wrap(
incident.narrative.strip()))
fh.write("[{0.report_id}]\n"
"date={0.date!s}\n"
"aircraft_id={0.aircraft_id}\n"
"aircraft_type={0.aircraft_type}\n"
"airport={airport}\n"
"pilot_percent_hours_on_type="
"{0.pilot_percent_hours_on_type}\n"
"pilot_total_hours={0.pilot_total_hours}\n"
"midair={0.midair:d}\n"
".NARRATIVE_START.\n{narrative}\n"
".NARRATIVE_END.\n\n".format(incident,
airport=incident.airport.strip(),
narrative=narrative))
return True
except EnvironmentError as err:
print("{0}: export error: {1}".format(
os.path.basename(sys.argv[0]), err))
return False
finally:
if fh is not None:
fh.close()
class Incident(object):
def __init__(self, report_id, date, airport, aircraft_id, aircraft_type,
pilot_percent_hours_on_type, pilot_total_hours, midair,
narrative=""):
assert len(report_id) >= 8 and len(report_id.split()) == 1,\
"invalid report ID"
self.__report_id = report_id
self.date = date
self.airport = airport
self.aircraft_id = aircraft_id
self.aircraft_type = aircraft_type
self.pilot_percent_hours_on_type = pilot_percent_hours_on_type
self.pilot_total_hours = pilot_total_hours
self.midair = midair
self.narrative = narrative
@property
def date(self):
return self.__date
@date.setter
def date(self, date):
assert isinstance(date, datetime.date), "invalid date"
self.__date = date
# заполняем коллекцию IncidentCollection данными
a = IncidentCollection(report_id='00000001',\
date=datetime.date(2007, 6, 12),
airport='USA airport', aircraft_id="bebebe",
Aircraft_type="LEGAL", pilot_percent_hours_on_type="pilot_percent_hours_on_type 12%",
pilot_total_hours="pilot_total_hours 1200", midair=True, narrative="sdasasdsa asdasdasdas\nfewfewfwefwefwefewfddsf")
a.export_text("/home/user/123.txt")
Press ENTER or type command to continue
Traceback (most recent call last):
File "python.sh", line 3932, in <module>
a.export_text("/home/user/123.txt")
File "python.sh", line 3837, in export_text
incident.narrative.strip()))
AttributeError: 'str' object has no attribute 'narrative'
shell returned 1
Отредактировано remoshka (Ноя. 22, 2014 14:23:14)
Офлайн
Здесь Вы выдаете ключи словаря, являющимися строками, по одному
def values(self): for report_id in self.keys(): yield self[report_id]
for incident in self.values(): narrative = "\n".join(wrapper.wrap( incident.narrative.strip()))
Офлайн
# создаем файл данных инцидентов
# report_id = str max 8
# date = datetime.date
# airport = str непустое, без символов перевода строки
# aircraft_id = str непустое без символов перевода строки
# aircraft_type = str непустое, без символов перевода строки
# pilot_percent_hours_on_type = float в диапазоне от 0.0 до 100.0
# pilot_total_hours = int положительное ненулевое значение
# midair = bool
# narrative = str многострочный текст
import os
import sys
import datetime
import textwrap
class IncidentError(Exception): pass
class Incident(object):
def __init__(self, report_id, date, airport, aircraft_id, aircraft_type,
pilot_percent_hours_on_type, pilot_total_hours, midair,
narrative=""):
assert len(report_id) >= 8 and len(report_id.split()) == 1,\
"invalid report ID"
self.__report_id = report_id
self.date = date
self.airport = airport
self.aircraft_id = aircraft_id
self.aircraft_type = aircraft_type
self.pilot_percent_hours_on_type = pilot_percent_hours_on_type
self.pilot_total_hours = pilot_total_hours
self.midair = midair
self.narrative = narrative
@property
def date(self):
return self.__date
@date.setter
def date(self, date):
assert isinstance(date, datetime.date), "invalid date"
self.__date = date
@property
def midair(self):
"Whether the incident involved another aircraft"
return self.__midair
@midair.setter
def midair(self, value):
assert isinstance(value, bool), "invalid midair value"
self.__midair = value
@property
def airport(self):
"The incident's airport"
return self.__airport
@airport.setter
def airport(self, airport):
assert airport and "\n" not in airport, "invalid airport"
self.__airport = airport
@property
def aircraft_id(self):
"The aircraft ID"
return self.__aircraft_id
@aircraft_id.setter
def aircraft_id(self, aircraft_id):
assert aircraft_id and "\n" not in aircraft_id, \
"invalid aircraft ID"
self.__aircraft_id = aircraft_id
@property
def aircraft_type(self):
"The aircraft type"
return self.__aircraft_type
@aircraft_type.setter
def aircraft_type(self, aircraft_type):
assert aircraft_type and "\n" not in aircraft_type, \
"invalid aircraft type"
self.__aircraft_type = aircraft_type
@property
def narrative(self):
"The incident's narrative"
return self.__narrative
@narrative.setter
def narrative(self, narrative):
self.__narrative = narrative
class IncidentCollection(dict):
def values(self):
for report_id in self.keys():
yield self[report_id]
def items(self):
for report_id in self.keys():
yield (report_id, self[report_id])
def __iter__(self):
for report_id in sorted(super(IncidentCollection, self).keys()):
yield report_id
keys = __iter__
def __reversed__(self):
for report_id in sorted(super().keys(), reverse=True):
yield report_id
def export_text(self, filename):
wrapper = textwrap.TextWrapper(initial_indent=" ", subsequent_indent=" ")
fh = None
try:
if(os.path.exists(filename)):
os.remove(filename)
fh = open(filename, "w")
narrative = "\n".join(wrapper.wrap(self['narrative'].strip()))
fh.write("[{report_id}]\n"
"date={date!s}\n"
"aircraft_id={aircraft_id}\n"
"aircraft_type={aircraft_type}\n"
"airport={airport}\n"
"pilot_percent_hours_on_type={pilot_percent_hours_on_type}\n"
"pilot_total_hours={pilot_total_hours}\n"
"midair={midair}\n"
".NARRATIVE_START\n{narrative}\n.NARRATIVE_END\n\n".format(
report_id=self['report_id'],date=self['date'],narrative=narrative,
aircraft_id=self['aircraft_id'], aircraft_type=self['aircraft_type'],
airport=self['airport'], pilot_percent_hours_on_type=self['pilot_percent_hours_on_type'],
pilot_total_hours=self['pilot_total_hours'], midair=self['midair']))
return True
except EnvironmentError as err:
print("{0}: export error: {1}".format(
os.path.basename(sys.argv[0]), err))
return False
finally:
if fh is not None:
fh.close()
# заполняем коллекцию IncidentCollection данными
a = IncidentCollection(report_id='00000001',\
date=datetime.date(2007, 6, 12),
airport='USA airport', aircraft_id="bebebe",
aircraft_type="LEGAL", pilot_percent_hours_on_type="pilot_percent_hours_on_type 11%",
pilot_total_hours="pilot_total_hours 1200", midair=True, narrative="sdasasdsa asdasdasdas\nfewfewfwefwefwefewfddsf")
b = IncidentCollection(report_id='00000002',\
date=datetime.date(2007, 6, 12),
airport='USA airport', aircraft_id="bebebe",
aircraft_type="LEGAL", pilot_percent_hours_on_type="pilot_percent_hours_on_type 12%",
pilot_total_hours="pilot_total_hours 1200", midair=True, narrative="sdasasdsa asdasdasdas\nfewfewfwefwefwefewfddsf")
a.export_text("/home/user/{report_id}.txt".format(report_id=a['report_id']))
narrative = "\n".join(wrapper.wrap(self['narrative'].strip()))
fh.write("[{report_id}]\n"
"date={date!s}\n"
"aircraft_id={aircraft_id}\n"
"aircraft_type={aircraft_type}\n"
"airport={airport}\n"
"pilot_percent_hours_on_type={pilot_percent_hours_on_type}\n"
"pilot_total_hours={pilot_total_hours}\n"
"midair={midair}\n"
".NARRATIVE_START\n{narrative}\n.NARRATIVE_END\n\n".format(
report_id=self['report_id'],date=self['date'],narrative=narrative,
aircraft_id=self['aircraft_id'], aircraft_type=self['aircraft_type'],
airport=self['airport'], pilot_percent_hours_on_type=self['pilot_percent_hours_on_type'],
pilot_total_hours=self['pilot_total_hours'], midair=self['midair']))
Отредактировано remoshka (Ноя. 22, 2014 19:43:48)
Офлайн