Alpha-Version entstanden aus purer Langeweile:
Update #4:
#! /usr/bin/env python3
#
# Reads values from a text file as described in
# <https://forum.archlinux.de/viewtopic.php?id=28974>
#
# (C) 2016: Richard Neumann
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
"""morilaval
Usage:
morilaval <file> <line>
"""
from docopt import docopt
from sys import stderr
__version__ = '0.1.4'
class MorilaRecord():
"""Wrapper class for data records of the MorilaFile"""
COLUMNS = ['G', 'X', 'Y', 'Z', 'F'] # Available record variables
def __init__(self, line):
self.line = line
def __str__(self):
lines = []
d = self.dict
for column in self.COLUMNS:
try:
value = d[column]
except KeyError:
pass
else:
line = '{0}={1}'.format(column, value)
lines.append(line)
return '\n'.join(lines)
def __getitem__(self, column):
if column not in self.COLUMNS:
raise KeyError(
"Column must be one of {0}, not '{1}'".format(
self.COLUMNS, column))
else:
return self.dict[column]
def __getattr__(self, attr):
if attr in self.COLUMNS:
return float(self[attr].replace(',', '.'))
else:
return super().__getattr__(attr)
def __iter__(self):
for column in self.COLUMNS:
yield getattr(self, column)
@property
def segments(self):
return self.line.split()
@property
def dict(self):
result = {}
for segment in self.segments:
for column in self.COLUMNS:
if segment.startswith(column):
_, value = segment.split(column)
result[column] = value
return result
class MorilaFile():
"""Parser for the respective data files"""
def __init__(self, path, encoding='utf-8'):
self.path = path
self.encoding = encoding
def __getitem__(self, index):
for i, morila_record in enumerate(self.records):
if i == index:
return morila_record
else:
raise IndexError(index)
def __iter__(self):
with open(self.path, 'r', encoding=self.encoding) as fh:
yield from fh
@property
def records(self):
for line in self:
if line.strip(): # Only process non-empty lines
yield MorilaRecord(line)
if __name__ == '__main__':
options = docopt(__doc__)
path = options['<file>']
line = options['<line>']
try:
line = int(line)
except ValueError:
print('ERROR: <line> must be an integer value', file=stderr)
exit(1)
else:
morila_file = MorilaFile(path)
morila_record = morila_file[line]
print(morila_record)