Skip to content

Tamara Zhordaniya #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
15 changes: 15 additions & 0 deletions 2018-komp-ling/practicals/maxmatch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
def maxmatch(sents, dictionary):
if not sents:
return []
for i in range(len(sents)-1, -1, -1):
word = sents[:i+1]
remains = sents[i+1:]
if word in dictionary:
return [word] + maxmatch(remains, dictionary)

else:
word = sents[0]
remains = sents[1:]
return [word] + maxmatch(remains, dictionary)


23 changes: 23 additions & 0 deletions 2018-komp-ling/practicals/maxmatch_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# maxmatch

1. Словарь из файла я извлекла с помощью команды sed '/^#/'d | cut -f2 -d' '

2. С максматчем было сложнее! Так как я новичок в программировании, я решила выбрать самый простой и очевидный скрипт. Рекурсивная функция получает на вход:
* предложения для обработки
* словарь токенов.
С помощью шага -1 с конца предложения каждый цикл отсчитывает один символ, после чего срез [от начала предложения : до символа] сравнивается с токенами из словаря. Найденное слово возвращается, после чего поиск продолжается по срезу [последний токен слова+1 :] Если слово не найдено в словаре, возвращается односимвольное слово.
Я очень хотела сделать код удобным в использовании, поэтому пыталась сделать:
if __name__ == '__main__':
sents = sys.argv[1]
dictionary = sys.argv[2]
maxmatch(sents, dictionary)

Но...У меня не получилось, поэтому инструкция по использованию выглядит примерно так:

* Открыть список предложений и словарь в питоне
* Запустить функцию с аргументами (предложения, словарь)
* ???????
* PROFIT!!!!

3. WER: 7.39%
Стоит признаться - WER тестировал не все мои данные, а только первые 20 предложений. К сожалению, мощность моего компьютера не могла мне позволить обработать все
38 changes: 38 additions & 0 deletions 2018-komp-ling/practicals/segmentation_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
**Pragmatic Segmenter** - сегментатор, работающий на правилах. Мне было трудно заставить его наконец работать, но когда у меня получилось, я была приятно удивлена.
Он правильно нашел ВСЕ предложения, но тут есть нюансы, о которых необходимо упомянуть. Например:
* _Anarchist historian George Woodcock reports: "The annual Congress of the International had not taken place in 1870 owing to the outbreak of the Paris Commune, and in 1871 the General Council called only a special conference in London. One delegate was able to attend from Spain and none from Italy, while a technical excuse – that they had split away from the Fédération Romande – was used to avoid inviting Bakunin's Swiss supporters. Thus only a tiny minority of anarchists was present, and the General Council's resolutions passed almost unanimously. Most of them were clearly directed against Bakunin and his followers"._
Сегментатор не размечал предложения, находящиеся внутри цитаты, как отдельные. Насколько я понимаю, вопрос о том, как стоит сегментатору поступать в таких ситуациях, является открытым, но я для себя решила, что такое поведение - верное.
Также он отлично справился с сокращениями, аббревиатурами и другими уловками пунктуации. Пример:
* _In Latin America in particular, "anarchists quickly became active in organising craft and industrial workers throughout South and Central America, and until the early 1920s most of the trade unions in Mexico, Brazil, Peru, Chile, and Argentina were anarcho-syndicalist in general outlook; the prestige of the Spanish C.N.T. as a revolutionary organisation was undoubtedly to a great extent responsible for this situation. The largest and most militant of these organisations was the Federación Obrera Regional Argentina [... it grew quickly to a membership of nearly a quarter of a million, which dwarfed the rival socialdemocratic unions"._
Еще пример:
* _The word "" is composed from the word "anarchy" and the suffix -ism, themselves derived respectively from the Greek , i.e. "anarchy" (from , "anarchos", meaning "one without rulers"; from the privative prefix ἀν- ("an-", i.e. "without") and , "archos", i.e. "leader", "ruler"; (cf. "archon" or , "arkhē", i.e. "authority", "sovereignty", "realm", "magistracy")) and the suffix or ("-ismos", "-isma", from the verbal infinitive suffix , "-izein")._

Результат: 100%


**Nltk punkt** - я использовала уже натренированный сегментатор для английского. К сожалению, он ошибся везде, где можно было это сделать. Разбивает предложения внутри цитат, не справляется с сокращениями и аббревиатурами.
Насчитал мне на шесть предложений больше, чем было. На зато более прост в использовании, чем Pragmatic Segmenter, ха-ха ;D

Вот его версии тех предложений, что я уже приводила выше:
* _In Latin America in particular, "anarchists quickly became active in organising craft and industrial workers throughout South and Central America, and until the early 1920s most of the trade unions in Mexico, Brazil, Peru, Chile, and Argentina were anarcho-syndicalist in general outlook; the prestige of the Spanish C.N.T._

_as a revolutionary organisation was undoubtedly to a great extent responsible for this situation._

* _The word "" is composed from the word "anarchy" and the suffix -ism, themselves derived respectively from the Greek , i.e._
_"anarchy" (from , "anarchos", meaning "one without rulers"; from the privative prefix ἀν- ("an-", i.e._
_"without") and , "archos", i.e._
_"leader", "ruler"; (cf._
_"archon" or , "arkhē", i.e._
_"authority", "sovereignty", "realm", "magistracy")) and the suffix or ("-ismos", "-isma", from the verbal infinitive suffix , "-izein")._

* _Anarchist historian George Woodcock reports: "The annual Congress of the International had not taken place in 1870 owing to the outbreak of the Paris Commune, and in 1871 the General Council called only a special conference in London._

_One delegate was able to attend from Spain and none from Italy, while a technical excuse – that they had split away from the Fédération Romande – was used to avoid inviting Bakunin's Swiss supporters._

_Thus only a tiny minority of anarchists was present, and the General Council's resolutions passed almost unanimously._
_Most of them were clearly directed against Bakunin and his followers"._

Результат: 84%



24 changes: 24 additions & 0 deletions 2018-komp-ling/quizzes/quiz_1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
1. a, d

2. sed 's/\([a-zA-Z]\+\)\/\([a-zA-Z]\+\)/\1 \/ \2/g'

3. Пожалуй, главная проблема машинного обучения - это очень плохая интерпретируемость. К тому же, для использования машинного обучения с учителем необходим большой размеченный корпус, а для малых языков это не всегда выполнимо.

4. ИпрыгалибегалитанцевалСашапослерезультатовэкзамена
Правильная версия: И прыгал и бегал и танцевал Саша после оглашения результатов экзамена
Но maxmatch распознает как: И прыгали бегали танцевал Саша после оглашения результатов экзамена

5.
* a - ambiguous abbrevations with punctuation;
Пример:
В 1970 г. А.И. Солженицын стал лауреатом Нобелевской премии по литературе.

* c - sentences lacking separating punctuation;
Пример:
Здравствуйте
Очень был рад нашей встрече
Надеюсь мы увидимся когда-нибудь еще

* d - sentences not separated by whitespace;
Пример:
Здравствуйте.Очень был рад нашей встрече.Надеюсь мы увидимся когда-нибудь еще.
29 changes: 29 additions & 0 deletions Practical_3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
### Practical 3

1. Мой код (его можно посмотреть в файле *train.py*) состоит из шести функций. Input: размеченный корпус текстов, output - четыре столбца с частотностью, кол-вом употребления и словоформами. (output_pic)

* **conllu_open** обрабатывает корпус текстов и возвращает корпус построчно в виде списков.

* **data_count_table** принимает строки из **conllu_open** и создает большой словарь, вложенный в словарь, в котором содержатся все словоформы, теги и то, сколько раз каждая словоформа была употреблена с определенным тегом.

* **data_freq_table** принимает результат функции **data_count_table** и заменяет с значениях вложенного словаря *количество появления тегов на частотность их появления*

* **count_tag** принимает результат **data_count_table** и составляет отдельный словарь { тег : кол-во раз появления тега }

* **freq_tag** заменяет в словаре **count_tag** количества раз на частотность

* **nice_lists** извлекает из предыдущих четырех функций необходимую информацию и создает list of lists с итоговыми необходимыми значениями

В конце я представила данные в удобочитаемом виде:

```python
print('# P', ' '*6, 'count', ' '*4, 'tag', ' '*6, 'form', ' '*5)
for i in nice_lists():
for s in i:
x = str(s)
print(s, ' '*(10-len(x)), end='')
print('\n')
```

2. *What might be a simple improvement to the language model for languages with orthographic case ?*

Loading