[text] Text converting for TF-IDF Vectorizer

Viewer

copydownloadembedprintName: Text converting for TF-IDF Vectorizer
  1. import nltk
  2. nltk.download("stopwords")
  3. from nltk.corpus import stopwords
  4. from string import punctuation
  5. english_stopwords = stopwords.words('english')
  6. from nltk.stem import WordNetLemmatizer
  7.  
  8. def remove_punct(text):
  9.     table = {33: ' ', 34: ' ', 35: ' ', 36: ' ', 37: ' ', 38: ' ', 39: ' ', 40: ' ', 41: ' ', 42: ' ', 43: ' ', 44: ' ', 45: ' ', 46: ' ', 47: ' ', 58: ' ', 59: ' ', 60: ' ', 61: ' ', 62: ' ', 63: ' ', 64: ' ', 91: ' ', 92: ' ', 93: ' ', 94: ' ', 95: ' ', 96: ' ', 123: ' ', 124: ' ', 125: ' ', 126: ' '}
  10.     return text.translate(table)
  11. lemma = WordNetLemmatizer()
  12.  
  13. train['text'] = train['text'].map(lambda x: x.lower())
  14. train['text'] = train['text'].map(lambda x: remove_punct(x))
  15. train['text'] = train['text'].map(lambda x: x.split(' '))
  16. train['text'] = train['text'].map(lambda x: [token for token in x if token not in english_stopwords\
  17.                                                                   and token != " " \
  18.                                                                   and token.strip() not in punctuation])
  19. train["text"] = train["text"].map(lambda x: [lemma.lemmatize(word) for word in x])
  20. train['text'] = train['text'].map(lambda x: ' '.join(x))

Editor

You can edit this paste and save as new:


File Description
  • Text converting for TF-IDF Vectorizer
  • Paste Code
  • 28 Mar-2023
  • 1.18 Kb
You can Share it: