IB111

Základy programování

František Lachman lachmanfrantisek@mail.muni.cz
cvičení 11
27. listopad 2018

Osnova

  • kontrolní otázky
  • práce s textem
  • práce se soubory
  • regulární výrazy
  • druhá vnitrosemestrálka (objekty, rekurze, řazení) ==4.12.==

Kontrolní otázky

Jakým způsobem pracujeme se soubory?

  1. Otevření souboru
  2. Práce se souborem
  3. Uzavření souboru

❓ K čemu slouží funkce open

Jaké má argumenty, jakou návratovou hodnotu ❓

In [19]:
soubor = open('this.txt', 'r')
# :
# Prace se souborem.
# :
soubor.close()

# Zde uz se souborem pracovat nesmime - je zavreny.

Módy

  • read
  • write
  • append

🔩 Další módy 🔩

r+/w+/a+, binární x textový přístup

❓ Pomocí jakých příkazů vypíšeme všechny řádky textového souboru ❓

In [20]:
my_file = open("this.txt")
print(my_file.readline())
print(my_file.readline())
print(my_file.readline())
print(my_file.readline())
# :
# :
my_file.close()
Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

In [21]:
my_file = open("this.txt")
line = my_file.readline()
while line:
    print(my_file.readline())
my_file.close()
Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-21-6c36e5e26a89> in <module>()
      2 line = my_file.readline()
      3 while line:
----> 4     print(my_file.readline())
      5 my_file.close()

/usr/lib/python3.7/site-packages/ipykernel/iostream.py in write(self, string)
    374             is_child = (not self._is_master_process())
    375             # only touch the buffer in the IO thread to avoid races
--> 376             self.pub_thread.schedule(lambda : self._buffer.write(string))
    377             if is_child:
    378                 # newlines imply flush in subprocesses

/usr/lib/python3.7/site-packages/ipykernel/iostream.py in schedule(self, f)
    201             self._events.append(f)
    202             # wake event thread (message content is ignored)
--> 203             self._event_pipe.send(b'')
    204         else:
    205             f()

/usr/lib64/python3.7/site-packages/zmq/sugar/socket.py in send(self, data, flags, copy, track, routing_id, group)
    389                                  copy_threshold=self.copy_threshold)
    390             data.group = group
--> 391         return super(Socket, self).send(data, flags=flags, copy=copy, track=track)
    392 
    393     def send_multipart(self, msg_parts, flags=0, copy=True, track=False, **kwargs):

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._send_copy()

/usr/lib64/python3.7/site-packages/zmq/backend/cython/checkrc.pxd in zmq.backend.cython.checkrc._check_rc()

KeyboardInterrupt: 

Funguje?

In [22]:
my_file = open("this.txt")
for line in my_file:
    print(line)
my_file.close()
Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

In [24]:
my_file = open("this.txt")
for line in my_file:
    if line.startswith("Complex"):
        raise Exception("Bad error during the file processing.")
my_file.close()
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-24-fbe6c8875e0d> in <module>()
      2 for line in my_file:
      3     if line.startswith("Complex"):
----> 4         raise Exception("Bad error during the file processing.")
      5 my_file.close()

Exception: Bad error during the file processing.

Práce v kontextu (with)

In [25]:
with open('this.txt') as soubor:
    for radek in soubor:
        print(radek)
Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

🔩 Fungování with pro zájemce 🔩

In [26]:
class Box:
    def __enter__(self):
        print("Open")
    
    def __exit__(self, *args):
        print("Close")

def my_box():
    with Box():
        print("Inside of the box")
        return
        print("Too late to be used.")


my_box()
Open
Inside of the box
Close

❓ Co vypíše následující kód ❓

In [29]:
with open('this.txt') as soubor:
    for radek in soubor:
        print(radek)
    for radek in soubor:
        print(radek)
Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

❓ Jaký je rozdíl mezi read, readline, readlines

🔩 Pohyb po souboru 🔩

kazeta

In [28]:
my_file = open("this.txt")

my_file.seek(13)
print(my_file.readline())

my_file.seek(0)
print(my_file.readline())
better than ugly.

Beautiful is better than ugly.

In [38]:
with open("something.txt", mode="w") as file_obj:
    file_obj.write("Beautiful is better than ugly.")
    file_obj.writelines(["Explicit is better than implicit.\n",
                        "Simple is better than complex."])

with open("something.txt") as other_file_obj:
    print(other_file_obj.read())
Beautiful is better than ugly.Explicit is better than implicit.
Simple is better than complex.

❓ Jak můžeme číst standardní vstup a vypisovat na standardní výstup❓

In [35]:
import sys
print(sys.stdin.readlines())
sys.stdout.write("Hello!")
[]
Hello!

Uveďte příklady použití následujících vnořených datových struktur:

  • ### slovník seznamů,
  • ### slovník slovníků,
  • ### seznam seznamů.

Jaký je význam split a join? Uveďte příklad použití.


In [ ]:
"a b c\td   e".split()
In [ ]:
"a=b=c=d".split("=")
In [ ]:
"|".join(["a", "b", "c"])
In [ ]:
"-".join([])

Příklady

11.1.1. Nejčastější slova

Načtěte soubor sherlock-holmes.txt a vypište 10 nejčastěji se vyskytujících slov v textu. Pro zajímavost se omezte pouze na slova délky 3 a více.

In [2]:
def most_freq_words(filename):
    pass

most_freq_words('sherlock-holmes.txt')

11.1.4. Podmíněná frekvenční analýza

Pro každé písmeno v textu vypište 5 písmen, které za ním následují nejčastěji. Můžete využít například soubor devatero_pohadek.txt.

In [3]:
def cond_freq_analysis(filename):
    pass

cond_freq_analysis('devatero_pohadek.txt')

11.1.7. Analýza jmen

Načtěte soubor jmena.csv. Implementujte funkci most_common_names(filename), která ze souboru vypíše count nejčastěji užívaných jmen (globálně).

In [5]:
def most_common_names(filename, count):
    pass

most_common_names('jmena.csv', 10)

Regulární výrazy

In [7]:
import re

# kontrola, jestli retezec odpovida vzoru
print(bool(re.match(r'\w+@\w+\.\w+', 'me@email.com')))   # je retezec e-mail
print(bool(re.match(r'\w+@\w+\.\w+', 'me@notemail')))
True
False
In [ ]:
# hledí řetězce
string = 'smlouva c. 1854 plati od 12. 1. 1999 do 15. 10. 2015, coz je vice jak 15 let'
result = re.search(r'\d+', string)    # hledame prvni cislo
print(result.group())
print(re.findall(r'\d+', string))      # hledame vsechny cisla
In [ ]:
result = re.search(r'(\d{1,2})\. (\d{1,2})\. (\d{4})', string)  # hledame prvni datum
print(result.group(0))       # cely odpovidajici retezec
print(result.group(1))       # den - prvni skupina (oznacena závorkami)
print(result.group(2))       # mesic
print(result.group(3))       # rok

Druhá vnitrosemestrálka

Závěr

  • kontrolní otázky
  • práce s textem
  • práce se soubory
  • regulární výrazy
  • druhá vnitrosemestrálka (objekty, rekurze, řazení) ==4.12.==