新闻文本分析—数据处理与分析

文章目录

    • 1.学习目标
    • 2.数据读取
    • 3.数据分析
      • 3.1句子长度分析
      • 3.2新闻类别分类
      • 3.3字符分布统计
    • 4.结论
    • 5.作业

1.学习目标

接着上一篇学习了新闻文本分类的赛题理解,本次将对训练集数据进行处理与分析。
1.学习使用pandas读取赛题数据。
2.分析赛题数据的分布规律。

2.数据读取

使用pandas中的read_csv对赛题数据集进行读取。

import pandas as pd
train_df = pd.read_csv('train_set.csv',sep='\t')
train_df.head()
label text
0 2 2967 6758 339 2021 1854 3731 4109 3792 4149 15...
1 11 4464 486 6352 5619 2465 4802 1452 3137 5778 54...
2 3 7346 4068 5074 3747 5681 6093 1777 2226 7354 6...
3 2 7159 948 4866 2109 5520 2490 211 3956 5520 549...
4 3 3646 3055 3055 2490 4659 6065 3370 5814 2465 5...

数据以表格形式呈现,第一列为新闻的类别,第二列为新闻的字符。

3.数据分析

3.1句子长度分析

直接统计单词的个数:

%pylab inline
train_df['text_len'] = train_df['text'].apply(lambda x: len(x.split(' ')))
print(train_df['text_len'].describe())
Populating the interactive namespace from numpy and matplotlib
count    200000.000000
mean        907.207110
std         996.029036
min           2.000000
25%         374.000000
50%         676.000000
75%        1131.000000
max       57921.000000
Name: text_len, dtype: float64

每个句子平均由907个字符构成,最短的句子长度为2,最长的句子长度为57921。

根据句子长度绘制直方图:

import matplotlib.pyplot as plt
_ = plt.hist(train_df['text_len'], bins=200)
plt.xlabel('Text char count')
plt.title("Histogram of char count")

新闻文本分析—数据处理与分析_第1张图片

大部分句子的长度都几种在2000以内。

3.2新闻类别分类

对数据集的类别进行分布统计

train_df['label'].value_counts().plot(kind='bar')
plt.title('News class count')
plt.xlabel("category")

新闻文本分析—数据处理与分析_第2张图片

在数据集中标签的对应的关系如下:{‘科技’: 0, ‘股票’: 1, ‘体育’: 2, ‘娱乐’: 3, ‘时政’: 4, ‘社会’: 5, ‘教育’: 6, ‘财经’: 7, ‘家居’: 8, ‘游戏’: 9, ‘房产’: 10, ‘时尚’: 11, ‘彩票’: 12, ‘星座’: 13}

赛题的数据集类别分布不均匀。在训练集中科技类新闻最多,其次是股票类新闻,最少的新闻是星座新闻。

3.3字符分布统计

将训练集中所有的句子进行拼接进而划分为字符,并统计每个字符的个数。

from collections import Counter
all_lines = ' '.join(list(train_df['text']))
word_count = Counter(all_lines.split(" "))
word_count = sorted(word_count.items(), key=lambda d:d[1], reverse = True)

print(len(word_count))

print(word_count[0])

print(word_count[-1])

6869

(‘3750’, 7482224)

(‘3133’, 1)

训练集中总共包括6869个字,其中编号3750的字出现的次数最多,编号3133的字出现的次数最少。

4.结论

赛题中每个新闻包含的字符个数平均为1000个,也有些达到5w+;
赛题中新闻类别分布不均匀,文本共13类,科技类新闻样本量接近4w,星座类新闻样本量不到1k;
赛题总共包括6869个字符;

5.作业

1.假设字符3750,字符900和字符648是句子的标点符号,请分析赛题每篇新闻平均由多少个句子构成?
2.统计每类新闻中出现次数对多的字符

train_df['punctuation'] = train_df['text'].apply(lambda x:sum([x.count('3750'),x.count('900'),x.count('648')]))
train_df['punctuation'].mean()
79.80237
from collections import Counter
category_text_count = {}
for i in range(len(set(train_df['label']))):
    all_lines = ' '.join(list(train_df.loc[train_df['label']==1,'text']))
    count = Counter(all_lines.split(' '))
    category_text_count[i] = count.most_common(5)
for k, v in category_text_count.items():
    print(k,v)

新闻文本分析—数据处理与分析_第3张图片

你可能感兴趣的:(新闻文本分析—数据处理与分析)