tnews.py 4.0 KB
Newer Older
S
Steffy-zxf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
# coding:utf-8
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from collections import namedtuple
import io
import os
import csv

from paddlehub.dataset import InputExample, HubDataset
from paddlehub.common.downloader import default_downloader
from paddlehub.common.dir import DATA_HOME
from paddlehub.common.logger import logger

_DATA_URL = "https://bj.bcebos.com/paddlehub-dataset/tnews.tar.gz"


class TNews(HubDataset):
    """
K
kinghuin 已提交
35
    TNews is the chinese news classification dataset on Jinri Toutiao App.
S
Steffy-zxf 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
    """

    def __init__(self):
        self.dataset_dir = os.path.join(DATA_HOME, "tnews")
        if not os.path.exists(self.dataset_dir):
            ret, tips, self.dataset_dir = default_downloader.download_file_and_uncompress(
                url=_DATA_URL, save_path=DATA_HOME, print_progress=True)
        else:
            logger.info("Dataset {} already cached.".format(self.dataset_dir))

        self._load_train_examples()
        self._load_test_examples()
        self._load_dev_examples()

    def _load_train_examples(self):
        self.train_file = os.path.join(self.dataset_dir,
                                       "toutiao_category_train.txt")
        self.train_examples = self._read_file(self.train_file)

    def _load_dev_examples(self):
        self.dev_file = os.path.join(self.dataset_dir,
                                     "toutiao_category_dev.txt")
        self.dev_examples = self._read_file(self.dev_file)

    def _load_test_examples(self):
        self.test_file = os.path.join(self.dataset_dir,
                                      "toutiao_category_test.txt")
        self.test_examples = self._read_file(self.test_file)

    def get_train_examples(self):
        return self.train_examples

    def get_dev_examples(self):
        return self.dev_examples

    def get_test_examples(self):
        return self.test_examples

    def get_labels(self):
        return [
K
kinghuin 已提交
76 77
            '100', '101', '102', '103', '104', '106', '107', '108', '109',
            '110', '112', '113', '114', '115', '116'
S
Steffy-zxf 已提交
78 79
        ]

K
kinghuin 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    def get_label_name(self, id):
        label_name = {
            "100": "news_story",
            "101": "news_culture",
            "102": "news_entertainment",
            "103": "news_sports",
            "104": "news_finance",
            "106": "news_house",
            "107": "news_car",
            "108": "news_edu",
            "109": "news_tech",
            "110": "news_military",
            "112": "news_travel",
            "113": "news_world",
            "114": "stock",
            "115": "news_agriculture",
            "116": "news_game"
        }
        return label_name[id]

S
Steffy-zxf 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
    @property
    def num_labels(self):
        """
        Return the number of labels in the dataset.
        """
        return len(self.get_labels())

    def _read_file(self, input_file):
        """Reads a tab separated value file."""
        with io.open(input_file, "r", encoding="UTF-8") as file:
            examples = []
            for line in file:
                data = line.strip().split("_!_")
                example = InputExample(
K
kinghuin 已提交
114
                    guid=data[0], label=data[1], text_a=data[3])
S
Steffy-zxf 已提交
115 116 117 118 119 120 121 122 123
                examples.append(example)

            return examples


if __name__ == "__main__":
    ds = TNews()
    for e in ds.get_train_examples()[:10]:
        print("{}\t{}\t{}\t{}".format(e.guid, e.text_a, e.text_b, e.label))