03. Jupyter Notebook¶
ehemalige Veranstaltungen ia3.netz + ia3.data sowie ia4.Netz im Studiengang Interaktive Medien
(c) 2020/2021 Hochschule Augsburg - Fakultät für Informatik - Prof.Dr.Nik Klever
In [1]:
# Python 2:
print "Dies ist ein String", 4.5
File "<ipython-input-1-1e469bd26b80>", line 3 print "Dies ist ein String", 4.5 ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Dies ist ein String", 4.5)?
In [4]:
try:
x = 1/0
except SyntaxError, e:
print("Syntaxerror")
File "<ipython-input-4-9bf908040ab3>", line 3 except SyntaxError, e: ^ SyntaxError: invalid syntax
In [5]:
try:
x = 1/0
except SyntaxError as e:
print("Syntaxerror")
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-5-a379fedbf4b8> in <module>() 1 try: ----> 2 x = 1/0 3 except SyntaxError as e: 4 print("Syntaxerror") ZeroDivisionError: division by zero
In [6]:
try:
x = 1/0
except:
print("Error")
Error
In [8]:
try:
x = 1/0
except ZeroDivisionError as e:
print("ZeroDivisioError",e)
except:
print("Error")
ZeroDivisioError division by zero
In [10]:
try:
open("irgendeine Datei")
except ZeroDivisionError as e:
print("ZeroDivisioError",e)
except:
print("Error")
Error
In [11]:
try:
open("irgendeine Datei")
except ZeroDivisionError as e:
print("ZeroDivisioError",e)
except:
raise
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-11-cbd595ab3e45> in <module>() 1 try: ----> 2 open("irgendeine Datei") 3 except ZeroDivisionError as e: 4 print("ZeroDivisioError",e) 5 except: FileNotFoundError: [Errno 2] No such file or directory: 'irgendeine Datei'
In [12]:
try:
open("irgendeine Datei")
except ZeroDivisionError as e:
print("ZeroDivisioError",e)
except FileNotFoundError as e:
print("Ihre Eingabe eines Dateinamens ist falsch, die Datei wurde nicht gefunden")
Ihre Eingabe eines Dateinamens ist falsch, die Datei wurde nicht gefunden
In [13]:
a = 2/3
In [14]:
a
Out[14]:
0.6666666666666666
In [15]:
%%writefile uebergabe.py
print("Wir sind jetzt in uebergabe.py")
try:
print("__file__:",__file__)
except:
print("__file__ existiert nicht")
print("uebergabe.py: __name__",__name__)
if __name__ == "__main__":
print("jetzt habe ich uebergabe.py direkt aufgerufen")
else:
print("wir verlassen jetzt uebergabe.py")
Writing uebergabe.py
In [16]:
!python uebergabe.py
Wir sind jetzt in uebergabe.py __file__: uebergabe.py uebergabe.py: __name__ __main__ jetzt habe ich uebergabe.py direkt aufgerufen
In [17]:
%%writefile test.py
print("Wir sind jetzt in test.py")
import uebergabe
print("nach dem import von uebergabe")
print("test.py: __name__:",__name__)
Overwriting test.py
In [18]:
!python test.py
Wir sind jetzt in test.py Wir sind jetzt in uebergabe.py __file__: C:\Users\nikkl\uebergabe.py uebergabe.py: __name__ uebergabe wir verlassen jetzt uebergabe.py nach dem import von uebergabe test.py: __name__: __main__
In [28]:
import glob
import json
import pprint
def leseDatei(dateiname):
try:
datei = open(dateiname,"r")
gesamterText = datei.read()
datei.close()
return gesamterText
except IOError:
print("Die Datei {} wurde nicht gefunden".format(dateiname))
return None
x = glob.glob("*.ipynb")
print(x)
if len(x)>0: rs = leseDatei(x[0])
else: rs = "{}"
ipynb = json.loads(rs)
#pprint.pprint(ipynb)
ersteZelle = ipynb['cells'][0]
print(ersteZelle['cell_type'])
print(ersteZelle['source'])
pprint.pprint(ipynb)
['01. Jupyter Notebook.ipynb', '02. Jupyter Notebook.ipynb', '03. Jupyter Notebook.ipynb']
code
['8+9']
{'cells': [{'cell_type': 'code',
'execution_count': 1,
'metadata': {},
'outputs': [{'data': {'text/plain': ['17']},
'execution_count': 1,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['8+9']},
{'cell_type': 'code',
'execution_count': 5,
'metadata': {},
'outputs': [],
'source': ['a = 2*7']},
{'cell_type': 'code',
'execution_count': 6,
'metadata': {},
'outputs': [{'data': {'text/plain': ['14']},
'execution_count': 6,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a']},
{'cell_type': 'code',
'execution_count': None,
'metadata': {},
'outputs': [],
'source': []},
{'cell_type': 'markdown',
'metadata': {},
'source': ['# Überschrift\n',
'\n',
'## Unterüberschrift\n',
'\n',
'Ein entsprechender **Text in Bold** und in *italics* '
'ausgegeben wird']},
{'cell_type': 'code',
'execution_count': 9,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['14\n']}],
'source': ['print(a)']},
{'cell_type': 'code',
'execution_count': 10,
'metadata': {},
'outputs': [{'data': {'text/plain': ['int']},
'execution_count': 10,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['type(a)']},
{'cell_type': 'code',
'execution_count': 11,
'metadata': {},
'outputs': [],
'source': ['import os']},
{'cell_type': 'code',
'execution_count': 12,
'metadata': {},
'outputs': [{'ename': 'NameError',
'evalue': "name 'getpid' is not defined",
'output_type': 'error',
'traceback': ['\x1b[1;31m---------------------------------------------------------------------------\x1b[0m',
'\x1b[1;31mNameError\x1b[0m '
'Traceback (most recent call last)',
'\x1b[1;32m<ipython-input-12-c344a67d685c>\x1b[0m '
'in '
'\x1b[0;36m<module>\x1b[1;34m()\x1b[0m\n'
'\x1b[1;32m----> 1\x1b[1;33m '
'\x1b[0mgetpid\x1b[0m\x1b[1;33m(\x1b[0m\x1b[1;33m)\x1b[0m\x1b[1;33m\x1b[0m\x1b[0m\n'
'\x1b[0m',
'\x1b[1;31mNameError\x1b[0m: name '
"'getpid' is not defined"]}],
'source': ['getpid()']},
{'cell_type': 'code',
'execution_count': 13,
'metadata': {},
'outputs': [{'data': {'text/plain': ['7016']},
'execution_count': 13,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['os.getpid()']},
{'cell_type': 'code',
'execution_count': 14,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'C:\\\\Users\\\\nikkl'"]},
'execution_count': 14,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['os.getcwd()']},
{'cell_type': 'code',
'execution_count': 15,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ["<class 'int'>\n"]}],
'source': ['x=os.getpid()\n', 'print(type(x))']},
{'cell_type': 'code',
'execution_count': 16,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['True\n']}],
'source': ['if True:\n', ' print(True)']},
{'cell_type': 'code',
'execution_count': 17,
'metadata': {},
'outputs': [{'ename': 'IndentationError',
'evalue': 'expected an indented block '
'(<ipython-input-17-e69bf44c797e>, line 2)',
'output_type': 'error',
'traceback': ['\x1b[1;36m File '
'\x1b[1;32m"<ipython-input-17-e69bf44c797e>"\x1b[1;36m, '
'line \x1b[1;32m2\x1b[0m\n'
'\x1b[1;33m print(False)\x1b[0m\n'
'\x1b[1;37m ^\x1b[0m\n'
'\x1b[1;31mIndentationError\x1b[0m\x1b[1;31m:\x1b[0m '
'expected an indented block\n']}],
'source': ['if True:\n', 'print(False)']},
{'cell_type': 'code',
'execution_count': 18,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['1\n', '4\n', 'tab\n']}],
'source': ['if True:\n',
' print(1)\n',
' print(4)\n',
' print("tab")']},
{'cell_type': 'code',
'execution_count': 19,
'metadata': {},
'outputs': [{'data': {'text/plain': ['Type help() for interactive '
'help, or help(object) for '
'help about object.']},
'execution_count': 19,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['help']},
{'cell_type': 'code',
'execution_count': 22,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['\n',
"Welcome to Python 3.7's help utility!\n",
'\n',
'If this is your first time using Python, '
'you should definitely check out\n',
'the tutorial on the Internet at '
'https://docs.python.org/3.7/tutorial/.\n',
'\n',
'Enter the name of any module, keyword, or '
'topic to get help on writing\n',
'Python programs and using Python modules. '
'To quit this help utility and\n',
'return to the interpreter, just type '
'"quit".\n',
'\n',
'To get a list of available modules, '
'keywords, symbols, or topics, type\n',
'"modules", "keywords", "symbols", or '
'"topics". Each module also comes\n',
'with a one-line summary of what it does; to '
'list the modules whose name\n',
'or summary contain a given string such as '
'"spam", type "modules spam".\n',
'\n',
'help> quit\n',
'\n',
'You are now leaving help and returning to '
'the Python interpreter.\n',
'If you want to ask for help on a particular '
'object directly from the\n',
'interpreter, you can type "help(object)". '
'Executing "help(\'string\')"\n',
'has the same effect as typing a particular '
'string at the help> prompt.\n']}],
'source': ['help()']},
{'cell_type': 'code',
'execution_count': 23,
'metadata': {},
'outputs': [{'data': {'text/plain': ["['In',\n",
" 'Out',\n",
" '_',\n",
" '_1',\n",
" '_10',\n",
" '_13',\n",
" '_14',\n",
" '_19',\n",
" '_21',\n",
" '_4',\n",
" '_6',\n",
" '__',\n",
" '___',\n",
" '__builtin__',\n",
" '__builtins__',\n",
" '__doc__',\n",
" '__loader__',\n",
" '__name__',\n",
" '__package__',\n",
" '__spec__',\n",
" '_dh',\n",
" '_exit_code',\n",
" '_i',\n",
" '_i1',\n",
" '_i10',\n",
" '_i11',\n",
" '_i12',\n",
" '_i13',\n",
" '_i14',\n",
" '_i15',\n",
" '_i16',\n",
" '_i17',\n",
" '_i18',\n",
" '_i19',\n",
" '_i2',\n",
" '_i20',\n",
" '_i21',\n",
" '_i22',\n",
" '_i23',\n",
" '_i3',\n",
" '_i4',\n",
" '_i5',\n",
" '_i6',\n",
" '_i7',\n",
" '_i8',\n",
" '_i9',\n",
" '_ih',\n",
" '_ii',\n",
" '_iii',\n",
" '_oh',\n",
" 'a',\n",
" 'exit',\n",
" 'get_ipython',\n",
" 'os',\n",
" 'quit',\n",
" 'x']"]},
'execution_count': 23,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['dir()']},
{'cell_type': 'code',
'execution_count': 24,
'metadata': {},
'outputs': [{'data': {'text/plain': ["['__abs__',\n",
" '__add__',\n",
" '__and__',\n",
" '__bool__',\n",
" '__ceil__',\n",
" '__class__',\n",
" '__delattr__',\n",
" '__dir__',\n",
" '__divmod__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__float__',\n",
" '__floor__',\n",
" '__floordiv__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__getnewargs__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__index__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__int__',\n",
" '__invert__',\n",
" '__le__',\n",
" '__lshift__',\n",
" '__lt__',\n",
" '__mod__',\n",
" '__mul__',\n",
" '__ne__',\n",
" '__neg__',\n",
" '__new__',\n",
" '__or__',\n",
" '__pos__',\n",
" '__pow__',\n",
" '__radd__',\n",
" '__rand__',\n",
" '__rdivmod__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__rfloordiv__',\n",
" '__rlshift__',\n",
" '__rmod__',\n",
" '__rmul__',\n",
" '__ror__',\n",
" '__round__',\n",
" '__rpow__',\n",
" '__rrshift__',\n",
" '__rshift__',\n",
" '__rsub__',\n",
" '__rtruediv__',\n",
" '__rxor__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__sub__',\n",
" '__subclasshook__',\n",
" '__truediv__',\n",
" '__trunc__',\n",
" '__xor__',\n",
" 'bit_length',\n",
" 'conjugate',\n",
" 'denominator',\n",
" 'from_bytes',\n",
" 'imag',\n",
" 'numerator',\n",
" 'real',\n",
" 'to_bytes']"]},
'execution_count': 24,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['dir(a)']},
{'cell_type': 'code',
'execution_count': 25,
'metadata': {},
'outputs': [{'data': {'text/plain': ['4']},
'execution_count': 25,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a.bit_length()']},
{'cell_type': 'code',
'execution_count': 26,
'metadata': {},
'outputs': [{'data': {'text/plain': ["['DirEntry',\n",
" 'F_OK',\n",
" 'MutableMapping',\n",
" 'O_APPEND',\n",
" 'O_BINARY',\n",
" 'O_CREAT',\n",
" 'O_EXCL',\n",
" 'O_NOINHERIT',\n",
" 'O_RANDOM',\n",
" 'O_RDONLY',\n",
" 'O_RDWR',\n",
" 'O_SEQUENTIAL',\n",
" 'O_SHORT_LIVED',\n",
" 'O_TEMPORARY',\n",
" 'O_TEXT',\n",
" 'O_TRUNC',\n",
" 'O_WRONLY',\n",
" 'P_DETACH',\n",
" 'P_NOWAIT',\n",
" 'P_NOWAITO',\n",
" 'P_OVERLAY',\n",
" 'P_WAIT',\n",
" 'PathLike',\n",
" 'R_OK',\n",
" 'SEEK_CUR',\n",
" 'SEEK_END',\n",
" 'SEEK_SET',\n",
" 'TMP_MAX',\n",
" 'W_OK',\n",
" 'X_OK',\n",
" '_Environ',\n",
" '__all__',\n",
" '__builtins__',\n",
" '__cached__',\n",
" '__doc__',\n",
" '__file__',\n",
" '__loader__',\n",
" '__name__',\n",
" '__package__',\n",
" '__spec__',\n",
" '_execvpe',\n",
" '_exists',\n",
" '_exit',\n",
" '_fspath',\n",
" '_get_exports_list',\n",
" '_putenv',\n",
" '_unsetenv',\n",
" '_wrap_close',\n",
" 'abc',\n",
" 'abort',\n",
" 'access',\n",
" 'altsep',\n",
" 'chdir',\n",
" 'chmod',\n",
" 'close',\n",
" 'closerange',\n",
" 'cpu_count',\n",
" 'curdir',\n",
" 'defpath',\n",
" 'device_encoding',\n",
" 'devnull',\n",
" 'dup',\n",
" 'dup2',\n",
" 'environ',\n",
" 'error',\n",
" 'execl',\n",
" 'execle',\n",
" 'execlp',\n",
" 'execlpe',\n",
" 'execv',\n",
" 'execve',\n",
" 'execvp',\n",
" 'execvpe',\n",
" 'extsep',\n",
" 'fdopen',\n",
" 'fsdecode',\n",
" 'fsencode',\n",
" 'fspath',\n",
" 'fstat',\n",
" 'fsync',\n",
" 'ftruncate',\n",
" 'get_exec_path',\n",
" 'get_handle_inheritable',\n",
" 'get_inheritable',\n",
" 'get_terminal_size',\n",
" 'getcwd',\n",
" 'getcwdb',\n",
" 'getenv',\n",
" 'getlogin',\n",
" 'getpid',\n",
" 'getppid',\n",
" 'isatty',\n",
" 'kill',\n",
" 'linesep',\n",
" 'link',\n",
" 'listdir',\n",
" 'lseek',\n",
" 'lstat',\n",
" 'makedirs',\n",
" 'mkdir',\n",
" 'name',\n",
" 'open',\n",
" 'pardir',\n",
" 'path',\n",
" 'pathsep',\n",
" 'pipe',\n",
" 'popen',\n",
" 'putenv',\n",
" 'read',\n",
" 'readlink',\n",
" 'remove',\n",
" 'removedirs',\n",
" 'rename',\n",
" 'renames',\n",
" 'replace',\n",
" 'rmdir',\n",
" 'scandir',\n",
" 'sep',\n",
" 'set_handle_inheritable',\n",
" 'set_inheritable',\n",
" 'spawnl',\n",
" 'spawnle',\n",
" 'spawnv',\n",
" 'spawnve',\n",
" 'st',\n",
" 'startfile',\n",
" 'stat',\n",
" 'stat_result',\n",
" 'statvfs_result',\n",
" 'strerror',\n",
" 'supports_bytes_environ',\n",
" 'supports_dir_fd',\n",
" 'supports_effective_ids',\n",
" 'supports_fd',\n",
' '
"'supports_follow_symlinks',\n",
" 'symlink',\n",
" 'sys',\n",
" 'system',\n",
" 'terminal_size',\n",
" 'times',\n",
" 'times_result',\n",
" 'truncate',\n",
" 'umask',\n",
" 'uname_result',\n",
" 'unlink',\n",
" 'urandom',\n",
" 'utime',\n",
" 'waitpid',\n",
" 'walk',\n",
" 'write']"]},
'execution_count': 26,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['dir(os)']},
{'cell_type': 'code',
'execution_count': 27,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['Help on built-in function getcwd in module '
'nt:\n',
'\n',
'getcwd()\n',
' Return a unicode string representing '
'the current working directory.\n',
'\n']}],
'source': ['help(os.getcwd)']},
{'cell_type': 'code',
'execution_count': 28,
'metadata': {},
'outputs': [{'data': {'text/plain': ["['__call__',\n",
" '__class__',\n",
" '__delattr__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__le__',\n",
" '__lt__',\n",
" '__module__',\n",
" '__name__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__qualname__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__self__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" '__text_signature__']"]},
'execution_count': 28,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['dir(os.getcwd)']},
{'cell_type': 'code',
'execution_count': 30,
'metadata': {},
'outputs': [],
'source': ['text = "Dies" + " ist " + " ein " + "Satz"']},
{'cell_type': 'code',
'execution_count': 31,
'metadata': {},
'outputs': [{'data': {'text/plain': ['5']},
'execution_count': 31,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['text.find("ist")']},
{'cell_type': 'code',
'execution_count': 32,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'ist ein Satz'"]},
'execution_count': 32,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['text[5:]']},
{'cell_type': 'code',
'execution_count': 33,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies war ein Satz'"]},
'execution_count': 33,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['text.replace("ist","war")']},
{'cell_type': 'code',
'execution_count': 34,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies ist ein Satz'"]},
'execution_count': 34,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['text']},
{'cell_type': 'code',
'execution_count': 35,
'metadata': {},
'outputs': [],
'source': ['text = text.replace("ist","war")']},
{'cell_type': 'code',
'execution_count': 36,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies war ein Satz'"]},
'execution_count': 36,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['text']},
{'cell_type': 'code',
'execution_count': 39,
'metadata': {},
'outputs': [{'data': {'text/plain': ["['Dies', 'war', 'ein', "
"'Satz']"]},
'execution_count': 39,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['textliste = text.split()\n', 'textliste']},
{'cell_type': 'code',
'execution_count': 40,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies-war-ein-Satz'"]},
'execution_count': 40,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['"-".join(textliste)']},
{'cell_type': 'code',
'execution_count': 41,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies ist ein Satz'"]},
'execution_count': 41,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['"Dies ist ein Satz"']},
{'cell_type': 'code',
'execution_count': 42,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies ist ein Satz'"]},
'execution_count': 42,
'metadata': {},
'output_type': 'execute_result'}],
'source': ["'Dies ist ein Satz'"]},
{'cell_type': 'code',
'execution_count': 43,
'metadata': {},
'outputs': [{'data': {'text/plain': ['"Nik\'s Text"']},
'execution_count': 43,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['"Nik\'s Text"']},
{'cell_type': 'code',
'execution_count': 44,
'metadata': {},
'outputs': [{'data': {'text/plain': ['"Nik\'s Text"']},
'execution_count': 44,
'metadata': {},
'output_type': 'execute_result'}],
'source': ["'Nik\\'s Text'"]},
{'cell_type': 'code',
'execution_count': 46,
'metadata': {},
'outputs': [],
'source': ['langertext = """Dies ist ein\n',
'Text über mehrere\n',
'Zeilen\n',
'"""']},
{'cell_type': 'code',
'execution_count': 47,
'metadata': {},
'outputs': [{'data': {'text/plain': ["'Dies ist ein\\nText über "
"mehrere\\nZeilen\\n'"]},
'execution_count': 47,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['str(langertext)']},
{'cell_type': 'code',
'execution_count': 48,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['Dies ist ein\n',
'Text über mehrere\n',
'Zeilen\n',
'\n']}],
'source': ['print(langertext)']},
{'cell_type': 'code',
'execution_count': 49,
'metadata': {},
'outputs': [{'data': {'text/plain': ['"\'Dies ist ein\\\\nText '
'über '
'mehrere\\\\nZeilen\\\\n\'"']},
'execution_count': 49,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['repr(langertext)']},
{'cell_type': 'code',
'execution_count': 50,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['Dies ist ein\n',
'Text über mehrere\n',
'Zeilen\n',
'\n']}],
'source': ['print(str(langertext))']},
{'cell_type': 'code',
'execution_count': 51,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ["'Dies ist ein\\nText über "
"mehrere\\nZeilen\\n'\n"]}],
'source': ['print(repr(langertext))']},
{'cell_type': 'code',
'execution_count': 52,
'metadata': {},
'outputs': [],
'source': ['datei = open("test.txt","w")\n',
'datei.write(langertext)\n',
'datei.close()']},
{'cell_type': 'code',
'execution_count': 53,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['Dies ist ein\n',
'Text über mehrere\n',
'Zeilen\n',
'\n']}],
'source': ['datei = open("test.txt","r")\n',
'gesamterInhalt = datei.read()\n',
'datei.close()\n',
'print(gesamterInhalt)']},
{'cell_type': 'code',
'execution_count': 54,
'metadata': {},
'outputs': [{'data': {'text/plain': ['float']},
'execution_count': 54,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a = 4*3.5\n', 'type(a)']},
{'cell_type': 'code',
'execution_count': 55,
'metadata': {},
'outputs': [{'ename': 'SyntaxError',
'evalue': 'invalid syntax '
'(<ipython-input-55-692b18f84830>, line 4)',
'output_type': 'error',
'traceback': ['\x1b[1;36m File '
'\x1b[1;32m"<ipython-input-55-692b18f84830>"\x1b[1;36m, '
'line \x1b[1;32m4\x1b[0m\n'
'\x1b[1;33m except IOError, '
'e:\x1b[0m\n'
'\x1b[1;37m ^\x1b[0m\n'
'\x1b[1;31mSyntaxError\x1b[0m\x1b[1;31m:\x1b[0m '
'invalid syntax\n']}],
'source': ['try:\n',
' dateiname = "irgendeinName.irgendwas"\n',
' datei = open(dateiname,"r")\n',
'except IOError, e:\n',
' print(dateiname,"nicht verfügbar")']},
{'cell_type': 'code',
'execution_count': 58,
'metadata': {},
'outputs': [{'name': 'stdout',
'output_type': 'stream',
'text': ['2 No such file or directory\n',
'irgendeinName.irgendwas nicht '
'verfügbar\n']}],
'source': ['try:\n',
' dateiname = "irgendeinName.irgendwas"\n',
' datei = open(dateiname,"r")\n',
'except IOError as e:\n',
' print(e.errno,e.strerror)\n',
' print(dateiname,"nicht verfügbar")']},
{'cell_type': 'code',
'execution_count': 59,
'metadata': {},
'outputs': [],
'source': ['a = int(3.141)']},
{'cell_type': 'code',
'execution_count': 60,
'metadata': {},
'outputs': [{'data': {'text/plain': ['3']},
'execution_count': 60,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a']},
{'cell_type': 'code',
'execution_count': 61,
'metadata': {},
'outputs': [{'data': {'text/plain': ['3']},
'execution_count': 61,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a = int(3.6789)\n', 'a']},
{'cell_type': 'code',
'execution_count': 62,
'metadata': {},
'outputs': [{'data': {'text/plain': ['3.141']},
'execution_count': 62,
'metadata': {},
'output_type': 'execute_result'}],
'source': ['a = float("3.141")\n', 'a']},
{'cell_type': 'code',
'execution_count': 63,
'metadata': {},
'outputs': [{'ename': 'ValueError',
'evalue': 'could not convert string to float: '
"'3.45€'",
'output_type': 'error',
'traceback': ['\x1b[1;31m---------------------------------------------------------------------------\x1b[0m',
'\x1b[1;31mValueError\x1b[0m '
'Traceback (most recent call last)',
'\x1b[1;32m<ipython-input-63-bc731ef2a1a1>\x1b[0m '
'in '
'\x1b[0;36m<module>\x1b[1;34m()\x1b[0m\n'
'\x1b[1;32m----> 1\x1b[1;33m '
'\x1b[0ma\x1b[0m \x1b[1;33m=\x1b[0m '
'\x1b[0mfloat\x1b[0m\x1b[1;33m(\x1b[0m\x1b[1;34m"3.45€"\x1b[0m\x1b[1;33m)\x1b[0m\x1b[1;33m\x1b[0m\x1b[0m\n'
'\x1b[0m\x1b[0;32m 2\x1b[0m '
'\x1b[0ma\x1b[0m\x1b[1;33m\x1b[0m\x1b[0m\n',
'\x1b[1;31mValueError\x1b[0m: could not '
"convert string to float: '3.45€'"]}],
'source': ['a = float("3.45€")\n', 'a']},
{'cell_type': 'code',
'execution_count': None,
'metadata': {},
'outputs': [],
'source': []}],
'metadata': {'kernelspec': {'display_name': 'Python 3',
'language': 'python',
'name': 'python3'},
'language_info': {'codemirror_mode': {'name': 'ipython',
'version': 3},
'file_extension': '.py',
'mimetype': 'text/x-python',
'name': 'python',
'nbconvert_exporter': 'python',
'pygments_lexer': 'ipython3',
'version': '3.7.0'}},
'nbformat': 4,
'nbformat_minor': 2}
In [29]:
%%HTML
<b><i>Dies ist ein Text</b></i>
Dies ist ein Text
In [31]:
%%HTML
<b><i>Dies ist ein Text</i></b>
Dies ist ein Text
In [33]:
%%HTML
<html>
<head>
<title>E-Mail</title>
</head>
<body>
<table>
<tr><th>Empfänger</th><td>Henning Stoyke</td></tr>
<tr><th>Absender</th><td>Nik Klever </td></tr>
<tr><th>Thema</th>
<td>Wie war dein Urlaub ? </td>
</tr>
<tr><th>Datum</th><td>1.10.2009</td></tr>
<tr><th>Nachricht</th>
<td>
<pre>Hallo Henning, ich hoffe,
du hattest einen tollen Urlaub ?
Bis bald, Nik</pre>
</td>
</tr>
</table>
</body>
</html>
| Empfänger | Henning Stoyke |
|---|---|
| Absender | Nik Klever |
| Thema | Wie war dein Urlaub ? |
| Datum | 1.10.2009 |
| Nachricht |
Hallo Henning, ich hoffe, du hattest einen tollen Urlaub ? Bis bald, Nik |
In [34]:
%%html
<html>
<head>
<title>Stadt - Land - Fluß</title>
</head>
<body>
<table>
<tr><th>Stadt<td>Augsburg</td></th></tr>
<tr><th>Land<td>Bayern</td></th></tr>
<tr><th>Fluß<td>Lech</td></th></tr>
<tr><th>Bedeutender Künstler<td>Bertold Brecht</td></th></tr>
<tr><th>Bedeutende Persönlichkeit<td>Fugger</td></th></tr>
</table>
</body>
</html>
| Stadt | Augsburg |
|---|---|
| Land | Bayern |
| Fluß | Lech |
| Bedeutender Künstler | Bertold Brecht |
| Bedeutende Persönlichkeit | Fugger |
In [4]:
%%writefile kontakte.dtd
<!ELEMENT Kontakte (Kontakt*)>
<!ELEMENT Kontakt (Person, Kontaktdaten*, Notizzettel*)>
<!ATTLIST Kontakt
Markierung (wichtig|unwichtig|sonstiges) "sonstiges"
Typ CDATA #IMPLIED>
<!ELEMENT Person (Name?, Vorname+, Geburtsname?,
Titel*, Namenszusatz?)>
<!ATTLIST Person
Geschlecht (männlich|weiblich|sonstiges) "sonstiges"
Geburtstag CDATA #REQUIRED>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Vorname (#PCDATA)>
<!ELEMENT Geburtsname (#PCDATA)>
<!ELEMENT Titel (#PCDATA)>
<!ELEMENT Namenszusatz (#PCDATA)>
<!ELEMENT Adresse (Strasse?, Hausnummer?, Plz?, Ort?,
Land?, Zusatzinfo?, Postfach?)>
<!ELEMENT Strasse (#PCDATA)>
<!ELEMENT Hausnummer (#PCDATA)>
<!ELEMENT Plz (#PCDATA)>
<!ELEMENT Ort (#PCDATA)>
<!ELEMENT Land (#PCDATA)>
<!ELEMENT Zusatzinfo (#PCDATA)>
<!ELEMENT Postfach (#PCDATA)>
<!ELEMENT Kontaktdaten (Adresse?, Telefonnummer*, EMail*, Überschrift*)>
<!ATTLIST Kontaktdaten
Typ (privat|geschäftlich|sonstiges) "sonstiges">
<!ELEMENT Telefonnummer (#PCDATA)>
<!ATTLIST Telefonnummer
Typ (mobil|festnetz|sonstiges) "festnetz">
<!ELEMENT EMail (#PCDATA)>
<!ELEMENT Notizzettel (#PCDATA)>
<!ELEMENT Überschrift (#PCDATA)>
Overwriting kontakte.dtd
In [5]:
%%writefile kontakte.xml
<?xml version="1.0"?>
<!DOCTYPE Kontakte SYSTEM "kontakte.dtd">
<Kontakte>
<Kontakt Typ="kein Freund" Markierung="unwichtig">
<Person Geschlecht="männlich"
Geburtstag="1.1.1970">
<Name>Mustermann</Name>
<Vorname>Max</Vorname>
<Geburtsname></Geburtsname>
<Titel>Lord</Titel>
<Namenszusatz></Namenszusatz>
</Person>
<Kontaktdaten Typ="geschäftlich">
<Adresse>
<Strasse>Unter der Brücke</Strasse>
<Hausnummer>10</Hausnummer>
<PLZ>86150</PLZ>
<Ort>Augsburg</Ort>
<Land>Bayern</Land>
<Zusatzinfo>Schwaben</Zusatzinfo>
<Postfach></Postfach>
</Adresse>
<Telefonnummer>123456789</Telefonnummer>
<Telefonnummer Typ="mobil">0190-987654321</Telefonnummer>
<EMail>Lord.Mustermann@hs-augsburg.de</EMail>
</Kontaktdaten>
<Kontaktdaten Typ="privat">
<Adresse>
<Strasse>Unter der Lechbrücke</Strasse>
<Hausnummer>2</Hausnummer>
<Plz>86150</Plz>
<Ort>Augsburg</Ort>
<Land>Bayern</Land>
<Zusatzinfo>Schwaben</Zusatzinfo>
<Postfach></Postfach>
</Adresse>
<Telefonnummer>567890</Telefonnummer>
<Telefonnummer Typ="mobil">0160-23456790</Telefonnummer>
<EMail>Lord.Mustermann@web.de</EMail>
<Notizzettel>stinkt ein bißchen</Notizzettel>
</Kontaktdaten>
<Notizzettel></Notizzettel>
</Kontakt>
<Kontakt Typ="Freund" Markierung="wichtig">
<Person Geschlecht="männlich"
Geburtstag="1.1.1990">
<Name>Lehmann</Name>
<Vorname>Moritz</Vorname>
<Geburtsname></Geburtsname>
<Titel> </Titel>
<Namenszusatz></Namenszusatz>
</Person>
<Kontaktdaten Typ="geschäftlich">
<Adresse>
<Strasse>Friedberger Str.</Strasse>
<Hausnummer>2</Hausnummer>
<Plz>86161</Plz>
<Ort>Augsburg</Ort>
<Land>Bayern</Land>
<Zusatzinfo>Schwaben</Zusatzinfo>
<Postfach></Postfach>
</Adresse>
<Telefonnummer>5586-7900</Telefonnummer>
<Telefonnummer Typ="mobil">0170-987654321</Telefonnummer>
<EMail>Moritz.Lehmann@hs-augsburg.de</EMail>
</Kontaktdaten>
<Kontaktdaten Typ="privat">
<Adresse>
<Strasse>Badstrasse</Strasse>
<Hausnummer>20</Hausnummer>
<Plz>86150</Plz>
<Ort>Augsburg</Ort>
<Land>Bayern</Land>
<Zusatzinfo>Schwaben</Zusatzinfo>
<Postfach></Postfach>
</Adresse>
<Telefonnummer>8976890</Telefonnummer>
<Telefonnummer Typ="mobil">0161-12342345</Telefonnummer>
<EMail>m.lehmann@web.de</EMail>
<Überschrift>ÄÖüß</Überschrift>
</Kontaktdaten>
<Notizzettel></Notizzettel>
</Kontakt>
</Kontakte>
Overwriting kontakte.xml
In [7]:
#! /usr/bin/python
# -*- coding: utf-8 -*-
from xml.sax import make_parser, handler, SAXException, SAXParseException
class SAXBeispiel1(handler.ContentHandler):
def __init__(self):
pass
def startDocument(self):
print("document started")
def endDocument(self):
print("document ended")
parser = make_parser()
instanz = SAXBeispiel1()
instanz.startDocument()
#parser.setContentHandler(instanz)
#parser.parse('kontakte.xml')
document started
In [9]:
from xml.sax import make_parser, handler, SAXException, SAXParseException
class SAXBeispiel2(handler.ContentHandler):
def __init__(self):
self.xmldokument = ""
def startDocument(self):
self.xmldokument += "<?xml version='1.0'?>\n"
def endDocument(self):
print(self.xmldokument)
def startElement(self, name, attrs):
self.xmldokument += "<{}".format(name) # Beginn der Ausgabe des Elements
for attr in attrs.getNames():
self.xmldokument += ' {}="{}"'.format(attr,attrs.getValue(attr))
self.xmldokument += ">"
def characters(self, content):
self.xmldokument += content
def endElement(self, name):
self.xmldokument += "</{}>".format(name)
parser = make_parser()
instanz = SAXBeispiel2()
instanz.startElement()
#parser.setContentHandler(instanz)
#parser.parse('kontakte.xml')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-cd373cb535e1> in <module>() 26 parser = make_parser() 27 instanz = SAXBeispiel2() ---> 28 instanz.startElement() 29 #parser.setContentHandler(instanz) 30 #parser.parse('kontakte.xml') TypeError: startElement() missing 2 required positional arguments: 'name' and 'attrs'