<jupyter_start><jupyter_text>Why text is bad for you<jupyter_code>import pandas as pd

import re

pd.set_option('max_colwidth', 300)
df = pd.read_csv('../data/wiki/wiki.csv.gz', encoding='utf8', index_col=None)
df['text'] = df.text.str.extract(r'^(.*?)\.', expand=False)
df.head()<jupyter_output><empty_output><jupyter_text>So what can we do?<jupyter_code>import nltk
#nltk.download('all')
from nltk.tokenize import SpaceTokenizer
tokenizer = SpaceTokenizer()
tokenizer.tokenize('He takes long walks')
from nltk.stem.snowball import EnglishStemmer
stemmer = EnglishStemmer()
stemmer.stem('Walks')
def tokenize_only(text):
    tokens = tokenizer.tokenize(text)
    
    # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
    filtered_tokens = [token for token in tokens if re.search('[a-zA-Z]', token)]
    
    return filtered_tokens

def tokenize_and_stem(text):
    tokens = tokenize_only(text)
    stems = map(stemmer.stem, tokens)
    return stems<jupyter_output><empty_output><jupyter_text>Ok.. but, how does that help me?<jupyter_code>sample = df[df.name.isin(['4chan', '8chan', 'Aerosmith', 'Alabama', 'Texas'])]
sample
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(stop_words='english', min_df=2, tokenizer=tokenize_and_stem)
vec_text = tfidf_vectorizer.fit_transform(sample.text)
vec_text
pd.DataFrame(vec_text.toarray())
tfidf_vectorizer.get_feature_names()
tfidf_vectorizer.idf_
vec_df = pd.DataFrame(vec_text.toarray(), columns=tfidf_vectorizer.get_feature_names())
sample.reset_index(drop=True).join(vec_df)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13027522935779817, 'fraction_numerical': 0.004281345565749235, 'mean_word_length': 6.79047619047619, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '496774', 'license': 'MIT', 'n_tokens_mistral': 615, 'n_tokens_neox': 594, 'n_words': 110, 'path': 'notebooks/401-WorkingWithText.ipynb', 'repo_name': 'ohadravid/ml-tutorial', 'size': '1635'}