## 2020年3月4日水曜日

### Python - Reading and Writing Files - Multiline Records、リストのリスト

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 10(Reading and Writing Files)、Exercise 7の解答を求めてみる。

コード

```#!/usr/bin/env python3
from unittest import TestCase, main
from typing import TextIO, Union
from io import StringIO

print('7.')

def test(self):
compound1 = '''COMPND T1
ATOM 1 N 0.1 0.2 0.3
ATOM 2 N 0.2 0.1 0.0
END
'''
compound2 = '''COMPND T2
ATOM 1 A 0.1 0.2 0.3
ATOM 2 A 0.2 0.1 0.0
END
'''
comment = "CMNT ...\n"
blank_line = ' \n'
in_file = StringIO(compound1 + comment +
blank_line + compound2 + blank_line + blank_line + comment)
self.assertEqual(len(result), 2)
self.assertEqual(result[0], ['T1', ['N', '0.1', '0.2', '0.3'], [
'N', '0.2', '0.1', '0.0']])
self.assertEqual(result[1], ['T2', ['A', '0.1', '0.2', '0.3'], [
'A', '0.2', '0.1', '0.0']])

def skip(line: str) -> bool:
return line.startswith('CMNT') or line.isspace()

while True:
if not line:
return None
if skip(line):
continue
break
parts = line.split()
name = parts[1]
molecule: list = [name]
if skip(line):
continue
if line.startswith('END'):
break
parts = line.split()
molecule.append(parts[2:])
return molecule

result = []
while True:
if molecule is None:
break
result.append(molecule)
return result

if __name__ == "__main__":
main()
```

```% mypy sample7.py
Success: no issues found in 1 source file
% ./sample7.py -v
7.