TASK2

作者: _一杯凉白开 | 来源:发表于2019-05-13 17:38 被阅读0次

    任务要求:

    • 基本文本处理技能:中英文字符串处理(删除不相关的字符、去停用词);分词(结巴分词);词、字符频率统计。
    • 语言模型;unigrambigramtrigram频率统计。
    • jiebe分词介绍和使用
    1. 中英文字符串处理(删除不相关的字符、去停用词)
    • 以保留相关字符方式删除不相关字符
        for text in data['text']:
            for uchar in text:
                # 判断是否为汉字
                if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
                    continue
                 # 判断是否为数字
                if uchar >= u'\u0030' and uchar<=u'\u0039':    
                    continue
                # 判断是否为英文字母
                if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):     
                    continue
                else:
                    text = text.replace(uchar, '')
            content.append(text)
    
    • jieba分词
            text_jieba = jieba.cut(text, cut_all=False)
    

    cut_all 参数用来控制是否采用全模式

    • 去停用词
      使用中文停用词表
            for word in text_jieba:
                if word not in stop_words:
                    text.append(word)
    
    1. 词、字符频率统计
    def get_wordsCounter(data):
        all_content = []
        # 把所有的text放到一个list中
        for content in data:
            all_content.extend(content)
        # 对字符频率统计
        counter = Counter(all_content)
        count_pairs = counter.most_common(VOCAB_SIZE - 1)
        
        words_counter = pd.DataFrame([i[0] for i in count_pairs], columns={'words'})
        words_counter['counter'] = [i[1] for i in count_pairs]
        return words_counter
    
    1. 语言模型

    统计语言模型是一个单词序列上的概率分布,对于一个给定长度为m的序列,它可以为整个序列产生一个概率,即想办法找到一个概率分布,它可以表示任意一个句子或序列出现的概率。

    • unigram

      一元文法模型——上下文无关模型
      该模型只考虑当前词本身出现的概率,而不考虑当前词的上下文环境。
      P(w_1, w_2,...,w_m)=P(w_1)*P(w_2)*...*P(w_m)
      每个句子出现的概率为每个单词概率成绩

    • N-gram
      依赖于上下文环境的词的概率分布的统计计算机语言模型。可以理解为当前词的概率与前面的n个词有关系

      • bigram:当N=2时称为二元 bigram模型,当前词只与它前面的一个词相关,这样概率求解公式:
        P(w_1,w_2,...,w_m)=\prod_{i=1}^{m} P(w_i|w_{i-(n-1)},...,w_{i-1})=\prod_{i=1}^{m} P(w_i|w_{i-1})
      • trigram: 当N=3时称为三元trigram模型,同理当前词只与它前面的两个词相关

    完整代码

    # -*- coding: utf-8 -*-
    """
    Created on Mon May 13 13:49:10 2019
    
    @author: pc
    """
    
    import pandas as pd
    import jieba
    from collections import Counter
    
    TRAIN_PATH = 'E:/task2/cnews.train.txt'
    STOPWORDS_PATH = 'E:/task2/ChineseStopWords.txt'
    VOCAB_SIZE = 5000
    
    def read_file(file_name):
        '''
            读文件
        '''
        file_path = {'train': TRAIN_PATH}
        contents = []
        labels = []
        with open(file_path[file_name], 'r', encoding='utf-8') as f:
            for line in f:
                try:
                    labels.append(line.strip().split('\t')[0])
                    contents.append(line.strip().split('\t')[1])
                except:
                    pass
        data = pd.DataFrame()
        data['text'] = contents
        data['label'] = labels
        return data
    
    
    def get_stopwordslist(path):
        stopwords = [line.strip() for line in open(path, 'r', encoding='utf-8').readlines()]  
        return stopwords          
    
    
    def pre_data(data):
        content = []
        stop_words = get_stopwordslist(STOPWORDS_PATH)
        for text in data['text']:
            for uchar in text:
                # 判断是否为汉字
                if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
                    continue
                 # 判断是否为数字
                if uchar >= u'\u0030' and uchar<=u'\u0039':    
                    continue
                # 判断是否为英文字母
                if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):     
                    continue
                else:
                    text = text.replace(uchar, '')
            # jieba分词
            text_jieba = jieba.cut(text, cut_all=False)
            # 去停用词
            text = []
            for word in text_jieba:
                if word not in stop_words:
                    text.append(word)
            content.append(text)
        
        return content
    
    def get_wordsCounter(data):
        '''
            词,字符频率统计
        '''
        all_content = []
        # 把所有的text放到一个list中
        for content in data:
            all_content.extend(content)
        # 对字符频率统计
        counter = Counter(all_content)
        count_pairs = counter.most_common(VOCAB_SIZE - 1)
        
        words_counter = pd.DataFrame([i[0] for i in count_pairs], columns={'words'})
        words_counter['counter'] = [i[1] for i in count_pairs]
        return words_counter
            
    
    train = read_file('train')
    train = train.iloc[:100]
    content = pre_data(train)
    counter_words = get_wordsCounter(content)
    

    相关文章

      网友评论

          本文标题:TASK2

          本文链接:https://www.haomeiwen.com/subject/koylaqtx.html