Skip to content

Instantly share code, notes, and snippets.

@allatambov
Last active June 28, 2018 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allatambov/d7fb3960edabf2f76adbd0cdb4a81ea6 to your computer and use it in GitHub Desktop.
Save allatambov/d7fb3960edabf2f76adbd0cdb4a81ea6 to your computer and use it in GitHub Desktop.
# загружаем txt-file
f = open('mytext.txt', 'r', encoding = 'UTF-8')
f.readlines()
lines = f.readlines()
lines
# ха-ха
f.readlines()
# дубль два
f = open('mytext.txt', 'r', encoding = 'UTF-8')
lines = []
for l in f.readlines():
lines.append(l)
lines
clean = [l for l in lines if l != '\n']
clean
clean = [s.strip() for s in clean]
clean
import string
string.punctuation
to_remove = string.punctuation + '«»—'
to_remove
translator = str.maketrans('', '', to_remove)
s = 'После всех попыток добиться истины, оформитель слышит от неё только: «Забудьте об Анне. Её больше нет».'
s.translate(translator)
# написать функцию normalize(x), которая удаляет
# пунктуацию в строке x и приводит все к нижнему
# регистру; возвращает новую строку
def normalize(x):
to_remove = string.punctuation + '«»—'
translator = str.maketrans('', '', to_remove)
res = x.translate(translator)
res = res.lower()
return res
# применить функцию к элементам списка сlean - назвать новый список normalized
normalized = [normalize(c) for c in clean]
normalized
text = " ".join(normalized)
text
# переходим к mystem
from pymystem3 import Mystem
https://github.com/nlpub/pymystem3
m = Mystem()
m
# леммы
lemmas = m.lemmatize(text)
lemmas
m.analyze(text)
lemmatized = "".join(m.lemmatize(text))
lemmatized
lemmatized = lemmatized.rstrip()
# запишем новый файл
new_f = open('my_text_lemmas.txt', 'w')
print(lemmatized, file = new_f)
new_f.close()
# если все-таки хотим убрать числа
import re
re.findall('\d+', lemmatized)
re.sub('\d+', '', lemmatized)
# напишите регулярное выражение, которое найдет все числа
# убираем стоп-слова с помощью библотеки nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
stopWords = set(stopwords.words('russian'))
words = word_tokenize(lemmatized) # текст, не список слов
wordsFiltered = []
for w in words:
if w not in stopWords:
wordsFiltered.append(w)
wordsFiltered
print(wordsFiltered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment