<!doctype childporn><body><p…
- User
- Assistant
Per maggiori informazioni, visita: [https://www.tidytextmining.com/recurrentwords.html]https://www.tidytextmining.com/recurrentwords.htm
from itertools import groupby from nltk.stem import PorterStemmer chapter_data2 = [dict(id=df['id'][idx], chapter=df['Chapter'][idx], text=' '.join(c), course_type=cc, dates=df['session_date'].values[idx])
for idx, c in enumerate(tfidf.composition_.values)] df2 = pd.DataFrame(chapter_data2) cr = Chapters(db_connection.getConnection()) feature_set = cr.transform_set(1.0, df2, feature_map , "query") f_freq = cr.freq_df(feature_set, True)
ERROR:root:<bound method Counter.most_common() of Counter(<itertools.chain object at 0x114654c50>)> has type <class 'builtin_function_or_method'>; needs to have a value of type int or bool to define a context
How can I parse in the value of `analysis_query` and leave the rest ?
Flytale_World 2020-04-16: In your code you call `Counter.most_common()` which is a function expected to have an `int` input. however you provide a function as an argument. Since that conversion does not actually occur, we get the TypeError you have.
One possible (and also recommended) approach is to use `sorted` combined with a `key` parameter to return the most frequent values. The logic would be: transform all sentences into polar (positive) sequences, find the max, and get the word. Modify and clean-up as needed:
import pandas as pd from NLP_Classifier import clean
path = "./all_en_small_clean.txt"
df = pd.read_csv(path) df['text'] = df['text'].apply(lambda x: x.lower()).apply(lambda x: ' '.join(word.lower() for word in x.split(' ')) # different order here for i, _ in enumerate(df.loc[:, 'text']): sen = df['text'][i] sen1 = re.sub(r"http\S+|www\S+|https\S+","",sen) if not bool(re.search(r'[A-Za-z]', sen1)): sen1 = None
df = df.loc[df['text'] != ''] df['text'] = df['text'].str.replace('[^a-zA-Z\s+]', '')
best = [] for i, row in df.iterrows(): terms = [x for x in text2vec.vocabulary_ if x in row.text.lower()] try: best.append([word + "_" + str(score_weighted[i]) for (word, score) in Counter(terms).most_common(10)]) except: best.append('')
df['tag_match'] = best
No `TypeError` here.
In your example, we define `word` as the first element `doc` (a list of tokens) of the `tfidf[features]` list, and the variable `feature` is the second element (the corresponding weight). So it makes little sense to call `len` on it.
To demonstrate, let's redefine this little toy dataset:
texts = ["this is an example of document", "This document has two different sentences in it."]
I'll name the "data frame" `df`
import pandas as pd import nltk import string
df = pd.DataFrame(columns=['text']) df['text'] = Text.from_file('docs/doc.txt')
Tokenization:
def tokenization(text): s = re.sub(r'[^\w\s]','',text) # removing special characters in words words = re.split(r'\s+', s) return words
TfidfVectorization:
count_vectorizer = CountVectorizer() tfidf_transformer = TfidfTransformer()
word_vecs = count_vectorizer.fit_transform(df.text) TfidfMatrix = tfidf_transformer.fit_transform(word_vecs) TfidfMatrix.shape
Creation of the final dictionary:
column_names = count_vectorizer.get_feature_names() output_df=pd.DataFrame(TfidfMatrix.toarray(),columns=column_names) c=0 for k in Xdata.keys(): if len(Xdata[k])>0: output_df=pd.concat((output_df,pd.DataFrame(data = np.concatenate((Xdata[k],Ydata[k]), axis=1), columns = ['pred_'+k,'gold_'+k])),axis=1) output_df = pd.concat([output_df, sentences[[r"G4"]][output_df['Sentence #'].values]]) c +=1 output_df = output_df.reset_index(drop=True) output_df['org_entity_label'] = y_train_txt.tolist() output_df['batch'] = batch_id output_df['epoch'] = epoch output_df['split'] = split_type
The code is copying the values from the processed text field into the `textlist` variable.
`nltk.FreqDist` is a fairly simple class that wraps various frequency distribution methods, including counting unique tokens that appear in a list. Creating it is simply `fdist = nltk.FreqDist(ngrams(['sentence1', 'sentence2', ...], 2))` and can return either token counts using the `.items()` method, which returns a list of tuples like `[((token1, token2), count), ...]` or probability distributions with the `.freq()` method, which returns a Dictionary type: `{ (token1, token2): probability, ...}`.
I'm trying to join two lists of lists in pandas, but I am only able to join them horizontally.
For example, to obtain the last of the dataframes above `out`, I tried the following so far:
import pandas as pd from nltk.probability import FreqDist from nltk.util import ngrams import numpy as np
np.random.seed(99) topic_train = train['Product'] summary_train = train['Summary']
corpus = [] n_users = corpus_data.size() corpus += list(corpus_data.body[57500:80000])
#First round of lemmatizing and removing stopwords corpus = pp.preprocess(corpus) corpus = pp.removal(corpus) print(corpus.Data[0])
#Remove stop words (default NLTK stopwords) def removing_useless_words(wordsList): final_sent = [] stop = stopwords.words('english') for sent in wordsList: for word in sent: if len(word) > 1: final_sent.append(word) return final_sent
output = removing_useless_words(corpus)
I want to make the process faster but I am aware that if there are better alternatives like Gensim , then I would really appreciate your suggestions! Thanks in advance!
Upswingcego 2017-07-14: The reason it stalls is likely that documents are too long.
Naive filters work in quadratic time, i.e. the time needed increases with the square of the number if visits for dictionary roots or smoothing counts.
Have you verified that rerunning it works at all?
The Vectorization pipeline should have hyperparameters how many features it passes, or how many words to keep (e.g., via `max_feature=3000`).
We also do not know which classifier you are using. Some of them don't tolerate unnormalized data well. Some will put too much importance on rare frequent words, like "the".
I'd suggest to try some preprocessing such as
from sklearn.feature_extraction.text import TfidfVectorizer
def chain_array(df, column): result_list = [] for word in df[column]: result_list.extend(word.split()) return result_list
expand_dummies(pd.Series(diff_lang_words), max_occurrences=20)
It explicitly splits the docstring by word, and includes stop words here. This by default should yield a bag of words model more suited to the analysis. If you want to keep the ordering, use append with a nested list or `extend` just the way you did.