NLP—新闻文本分类比赛—Task2数据读取与分析

1、使用panda读取数据

2、对数据进行初步分析

    2.1、查看label的分布情况

    2.2、统计文本单词总数

    2.3、统计各个单词出现的次数

    2.4、根据符号进行句子的统计汇总

    2.5 对每个label 出现的单词进行统计汇总

```python

import numpy as np

import pandas as pd

import matplotlib as mpl

import matplotlib.pyplot as plt

import re

from collections import Counter

# 设置matplotlib画图显示中文

mpl.rcParams['font.sans-serif'] = ['KaiTi']

mpl.rcParams['font.serif'] = ['KaiTi']

pd.set_option('display.max_columns', 500)

pd.set_option('display.max_rows', 500)

pd.set_option('max_colwidth',5000)

%matplotlib inline

```

1、使用pandas读取数据,指定分隔符

```python

nlp_data = pd.read_csv('train_set.csv',sep='\t',encoding='utf-8')

nlp_data.head()

```

2、对数据进行初步分析

2.1、查看label的分布情况

```python

nlp_data['label'].value_counts().plot(kind='bar')

plt.title('新闻类别统计')

plt.xlabel("类别")

```

2.2、统计文本单词总数

```python

nlp_data['text_len'] = nlp_data['text'].apply(lambda x:len(x.split(' ')))

nlp_data['text_len'].describe()

```

```python

t = plt.hist(nlp_data['text_len'], bins=1000)

plt.xlabel('文本字数')

plt.xlim(0,6000)

plt.title("文本字符统计汇总")

```

```python

all_line = ' '.join(list(nlp_data['text']))

word_tuple = Counter(all_line.split(" "))

word_count = sorted(word_tuple.items(), key=lambda x:x[1], reverse = True)

print(word_count[0:10])

```

2.3、统计各个单词出现的次数

```python

nlp_data['unique_text'] = nlp_data['text'].apply(lambda x: ' '.join(list(set(x.split(' ')))))

all_line = ' '.join(list(nlp_data['text']))

words = Counter(all_line.split(" "))

word_counts = sorted(words.items(), key=lambda x:x[1], reverse = True)

print(word_counts[0:10])

```

2.4、根据符号进行句子的统计汇总

3750 648 900 出现的次数明显远远高于其他词,可能是标点符号,由此对数据进行分句处理

```python

nlp_data['sentence_num'] = nlp_data['text'].apply(lambda x:len(re.split("3750|648|900",x)))

```

2.5 对每个label 出现的单词进行统计汇总

对同label的新闻数据进行拼接,然后对每个类别的数据进行上面统计词频操作

```python

def word_cou(label_line):

    word_tuple = Counter(label_line.split(" "))

    word_count = sorted(word_tuple.items(), key=lambda x:x[1], reverse = True)

    return word_count[0:100]

= nlp_data.groupby(by='label').apply(lambda x:' '.join(map(str,x['text']))).reset_index()

nlp_label.columns = ['label','text']

nlp_label['word_count'] = nlp_label['text'].apply(word_cou)

```

```python

nlp_label['word_count'].head(14)

```

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容