Example #1
0
    def get_texts_stat(self, mode='train'):
        # Готовим данные
        env = Environment()
        if mode == 'train':
            file_res = env.filename_results_csv()
        if mode == 'test':
            file_res = env.filename_stat_test_csv()
        authors = pd.read_csv(env.filename_authors_csv(),
                              index_col='idauthor',
                              encoding='utf-8')

        data = pd.read_csv(file_res, index_col='idstat', encoding='utf-8')
        data.drop(columns=['file', 'idchunk'], inplace=True)
        columns = data.columns

        group = data.groupby(['idtext', 'idauthor', 'author', 'name'])
        group = group.agg({
            'sentences_text': ['mean'],
            'words_text': ['mean'],
            'sentence_mean': ['mean'],
            'sentences_chunk': ['mean'],
            'words_chunk': ['mean'],
            'words_uniq_chunk': ['mean'],
            'uniq_per_sent_chunk': ['mean'],
            'uniq_per_words_chunk': ['mean'],
            'NOUN': ['mean'],
            'ADJF': ['mean'],
            'ADJS': ['mean'],
            'COMP': ['mean'],
            'VERB': ['mean'],
            'INFN': ['mean'],
            'PRTF': ['mean'],
            'PRTS': ['mean'],
            'GRND': ['mean'],
            'NUMR': ['mean'],
            'ADVB': ['mean'],
            'NPRO': ['mean'],
            'PRED': ['mean'],
            'PREP': ['mean'],
            'CONJ': ['mean'],
            'PRCL': ['mean'],
            'INTJ': ['mean'],
            'predict': ['sum']
        })
        group.columns = columns[4:]
        group.reset_index(inplace=True)
        data = pd.merge(group,
                        authors,
                        on='idauthor',
                        how='left',
                        suffixes=('', '_author'))
        if mode == 'test':
            data['predict'] = data['predict'].astype(int)
        data = pd.merge(data,
                        authors,
                        left_on='predict',
                        right_on='idauthor',
                        how='left',
                        suffixes=('', '_predict'))
        return data
Example #2
0
 def stat(self):
     env = Environment()
     data = pd.DataFrame()
     file_stat = env.filename_results_csv()
     try:
         data = pd.read_csv(file_stat, index_col='idstat', encoding='utf-8')
     except:
         env.debug(1, ['Failed to read stat file:', file_stat])
     else:
         env.debug(1, ['Read stat file OK:', file_stat])
     #print(data)
     return data
Example #3
0
    def process_from_texts_file(self, aidtext, mode='process', max_words=0):
        env = Environment()
        file_res = env.filename_results_csv()
        dfres = pd.read_csv(
            file_res, index_col='idstat',
            encoding='utf-8')  #Файл для записи статистических результатов
        #dfres = env.downcast_dtypes(dfres)
        df_texts = pd.read_csv(env.filename_texts_csv(),
                               index_col='idtext',
                               encoding='utf-8')  #Реестр текстов
        mask = df_texts.index.isin(aidtext)
        df_texts = df_texts[mask]
        for index, row in df_texts.iterrows(
        ):  #Для каждого текста, который надо обработать
            file_txt = df_texts.at[index, 'filename']
            #Read text file
            env.debug(1, ['START file TXT:', file_txt])
            t_start = timer()
            #file = open(file_txt, 'r')
            file = codecs.open(file_txt, "r", "utf_8_sig")
            text = file.read().strip()
            file.close()
            # print(text)
            #Автор в обучающей выборке указанг
            idauthor = df_texts.at[index, 'idauthor']  #Автор
            name = df_texts.at[index, 'name']  #Название
            columns = dfres.columns
            if mode == 'process':  #если необходимо собрать информацию о тексте и записать её в results
                #Собственно обработка текста
                df_add = self.analyze_text(
                    columns, text, index, idauthor, name, file_txt,
                    max_words)  #Analyze text, get Series
                df_add.reset_index(drop=True, inplace=True)
                dfres = dfres.append(
                    df_add, ignore_index=True)  #Добавляем к файлу результатов
                dfres.reset_index(drop=True, inplace=True)
                dfres.index.name = 'idstat'
                #print(dfres)
                #return 0

            if mode == 'chunk_size':  # если необходимо определить размер chunk
                n_chunk_size = self.validate_chunk_size(
                    columns, text, index, idauthor, name, file_txt)
            t_end = timer()
            env.debug(1, [
                'END file TXT:', file_txt, 'time:',
                env.job_time(t_start, t_end)
            ])
            # print(dfres.head())
        #Сохраняем результат на диск
        if mode == 'process':
            #dfres = dfres.reset_index(drop=True)
            int_cols = [
                'idtext', 'idchunk', 'idauthor', 'sentences_text',
                'words_text', 'sentences_chunk', 'words_chunk',
                'words_uniq_chunk'
            ]
            for col in int_cols:
                dfres[col] = dfres[col].astype(int)
            #dfres = env.downcast_dtypes(dfres)
            dfres.to_csv(file_res, encoding='utf-8')