Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# matplotlib

Получение рангов для нашего текста

````
import matplotlib.pyplot as plt

freq = []
ranks = []

#load data
with open('./../freq.txt', 'r') as f:
f = f.readlines()
for line in f:
line = line.strip('\n')
(f, w) = line.split('\t')
freq.append((int(f), w))

freq.sort(reverse=True)

#ranking data
rank = 1
min = freq[0][0]
for i in range(0, len(freq)):
if freq[i][0] < min:
rank +=1
min = freq[i][0]
ranks.append([rank, freq[i][0], freq[i][1]])

#do the plots
x = []
y = []
for line in ranks:
row = line
x.append(int(row[0]))
y.append(int(row[1]))
plt.plot(x, y, 'b*')
plt.show()
````
# ElementTree

### How would you get just the Icelandic line and the gloss line ?

````
for tier in root.findall('.//tier'):
if tier.attrib['id'] == 'n':
for item in tier.findall('.//item'):
if item.attrib['tag'] != 'T': # here is the condition
print(item.text)
````

# scikit learn

### Perceptron answers
````
- #хоругвь# incorrect class: 0 correct class: 1
- #обувь# incorrect class: 0 correct class: 1
- #морковь# incorrect class: 0 correct class: 1
- #бровь# incorrect class: 0 correct class: 1
- #церковь# incorrect class: 0 correct class: 1
0.982857142857142856
````
To improve the quiality of our model we should use MLP, or deeper (than 1 layer) models

# Screenscraping

done in __screencap.py__

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#дерево
import sys

def strip_html(h):
output = ''
inTag = False
for c in h:
if c == '<':
inTag = True
continue
if c == '>':
inTag = False
continue
if not inTag:
output += c
return output

stem = '_'
zkod = '_'
ipa = '_'


h1 = '_'
for line in sys.stdin.readlines():
line = line.strip()
text = strip_html(line)
if line.count('<h1>') > 0:
h1 = strip_html(line)
if h1 != 'Русский':
continue
if text.count('Корень:') > 0:
stem = text.split(':')[1].split(';')[0]
if text.count('МФА') > 0:
ipa = text.split(';')[3].split('&')[0]
if text.count('тип склонения') > 0:
zkod = text.split('тип склонения')[1].strip().split(' ')[0].strip("^")


if stem != '_' and zkod != '_' and ipa != '_':
print('%s\t%s\t%s' % (stem, zkod, ipa))
stem = '_'
zkod = '_'
ipa = '_'
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# matplotlib

Получение рангов для нашего текста

````
import matplotlib.pyplot as plt

freq = []
ranks = []

#load data
with open('./../freq.txt', 'r') as f:
f = f.readlines()
for line in f:
line = line.strip('\n')
(f, w) = line.split('\t')
freq.append((int(f), w))

freq.sort(reverse=True)

#ranking data
rank = 1
min = freq[0][0]
for i in range(0, len(freq)):
if freq[i][0] < min:
rank +=1
min = freq[i][0]
ranks.append([rank, freq[i][0], freq[i][1]])

#do the plots
x = []
y = []
for line in ranks:
row = line
x.append(int(row[0]))
y.append(int(row[1]))
plt.plot(x, y, 'b*')
plt.show()
````
# ElementTree

### How would you get just the Icelandic line and the gloss line ?

````
for tier in root.findall('.//tier'):
if tier.attrib['id'] == 'n':
for item in tier.findall('.//item'):
if item.attrib['tag'] != 'T': # here is the condition
print(item.text)
````

# scikit learn

### Perceptron answers
````
- #хоругвь# incorrect class: 0 correct class: 1
- #обувь# incorrect class: 0 correct class: 1
- #морковь# incorrect class: 0 correct class: 1
- #бровь# incorrect class: 0 correct class: 1
- #церковь# incorrect class: 0 correct class: 1
0.982857142857142856
````
To improve the quiality of our model we should use MLP, or deeper (than 1 layer) models

# Screenscraping

done in __screencap.py__

19 changes: 19 additions & 0 deletions 2018-komp-ling/practicals/segmentation-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!--
SPDX-License-Identifier: (CC-BY-SA-4.0 OR GFDL-1.3-or-later)
Copyright 2018 Nick Howell
-->

<div style="column-width: 30em">

<h1> Обзор двух библиотек по токенизированию предложений </h1>

В данном отчете было использованы две библиотеки по токенеизорванию спредложений из текста: pragmatic segmenter (Ruby) и NLTK (Python). В качестве тестового текста был использован кусок дампа русской Википедии.
<h2> Pragmatic segmenter (Ruby) </h2>
Pragmatic segmenter - это бибилотека для Ruby, основанная на правилах. При парсинге русской википедии данная библиотека показала качество ниже среднего. Большинство сокращений, инициалы имен и т.д. неправильно были разделены на предложения.
В общем библиотека больше расчитана на языки латинского алфавита.

<h2> NLTK (Python) </h2>

sent_tokenize() - это функция библиотеки NLTK по определению границ предложения. Но на самом деле это алгоритм машинного обучения без учителя, который можно обучить самомстоятельно. В бибилотеке NLTK уже есть набор pre-trained моделей, в том числе и для русского языка. В общем данная библиотека показала себя лучше, чем Ruby. Большинство сокращений и инициалов выделены правильно, единтсвенную проблему составляет сокращения с пробелами внутри.

</div>
19 changes: 19 additions & 0 deletions 2018-komp-ling/practicals/segmentation/segmentation-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!--
SPDX-License-Identifier: (CC-BY-SA-4.0 OR GFDL-1.3-or-later)
Copyright 2018 Nick Howell
-->

<div style="column-width: 30em">

<h1> Обзор двух библиотек по токенизированию предложений </h1>

В данном отчете было использованы две библиотеки по токенеизорванию спредложений из текста: pragmatic segmenter (Ruby) и NLTK (Python). В качестве тестового текста был использован кусок дампа русской Википедии.
<h2> Pragmatic segmenter (Ruby) </h2>
Pragmatic segmenter - это бибилотека для Ruby, основанная на правилах. При парсинге русской википедии данная библиотека показала качество ниже среднего. Большинство сокращений, инициалы имен и т.д. неправильно были разделены на предложения.
В общем библиотека больше расчитана на языки латинского алфавита.

<h2> NLTK (Python) </h2>

sent_tokenize() - это функция библиотеки NLTK по определению границ предложения. Но на самом деле это алгоритм машинного обучения без учителя, который можно обучить самомстоятельно. В бибилотеке NLTK уже есть набор pre-trained моделей, в том числе и для русского языка. В общем данная библиотека показала себя лучше, чем Ruby. Большинство сокращений и инициалов выделены правильно, единтсвенную проблему составляет сокращения с пробелами внутри.

</div>
42 changes: 42 additions & 0 deletions 2018-komp-ling/practicals/transliteration-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Practical 2: Transliteration (engineering)

<div style="column-width: 30em">

## Questions
What to do with ambiguous letters ? For example, Cyrillic `е' could be either je or e.

Can you think of a way that you could provide mappings from many characters to one character ?
For example sh → ш or дж → c ?
How might you make different mapping rules for characters at the beginning or end of the string ?


### Правила для транслитерации

Основная идея - это начинать транслитерацию со сложных, многобуквенных преобразований (ч - tch). Например:
>Шарик -- sh-арик -- sharik

Далее нужно заменить все гласные в начале и в конце слова (Я - ya).
>яблоко -- ya-блоко -- yabloko

После чего уже можно переходить на простые однобуквенные преобразования (у - u)
>мед -- med

## Методы
### Кодировка-декодировка с помощью KOI-8R

Транслитерация с помощью кодировки KOI-8R - не самый эффективный метод транслитерации текста.
Но он обеспечивает некоторые особенности, которые не доступны другим способам:

1)Возможность восстановить первоначальный текст

2)Правила кодировки уже заданы

Метод транслитерации с помощью KOI-8R представлен в файле transliterate_koi8r.py

### Кодировка-декодировка с помощью правил

Правила для транслетерации находятся в файле rules.txt.
В нем заданы правила для согланых, гласных, а также для гласных в начале слова.


</div>
44 changes: 44 additions & 0 deletions 2018-komp-ling/practicals/transliteration/rank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/python

import sys, getopt

def main(argv):
inputfile = ''
outputfile = 'ranked.txt'
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print( 'test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print( 'Input file is:', inputfile)
print( 'Output file is:', outputfile)

freq = []
with open(inputfile, 'r',encoding='utf8') as fd:
for line in fd.readlines():
line = line.strip('\n')
(f, w) = line.split('\t')
freq.append((int(f), w))
rank = 1
min = freq[0][0]
ranks = []
for i in range(0, len(freq)):
if freq[i][0] < min:
rank = rank + 1
min = freq[i][0]
ranks.append((rank, freq[i][0], freq[i][1]))

with open(outputfile, 'w+',encoding='utf8') as fd:
for w in vocab:
fd.write(ranks)

if __name__ == "__main__":
main(sys.argv[1:])
36 changes: 36 additions & 0 deletions 2018-komp-ling/practicals/transliteration/rules.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
я ya
ю yu
е ye
а a
б b
в v
г g
д d
е e
ё yo
ж zsh
з z
и i
й y
к k
л l
м m
н n
о o
п p
р r
с s
т t
у u
ф f
х h
ц ts
ч tch
ш ch
щ scsh
ъ '
ы uy
ь '
э a
ю u
я a
Loading