msra_ner.py 3.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16 17 18
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

19
import os
20
import codecs
21 22
import csv
import json
23
import six
24 25
from collections import namedtuple

26
from paddlehub.dataset import InputExample, HubDataset
W
wuzewu 已提交
27 28
from paddlehub.common.downloader import default_downloader
from paddlehub.common.dir import DATA_HOME
29
from paddlehub.common.logger import logger
W
wuzewu 已提交
30

Z
Zeyu Chen 已提交
31
_DATA_URL = "https://paddlehub-dataset.bj.bcebos.com/msra_ner.tar.gz"
32 33


34 35 36 37 38 39 40 41
class MSRA_NER(HubDataset):
    """
    A set of manually annotated Chinese word-segmentation data and
    specifications for training and testing a Chinese word-segmentation system
    for research purposes.  For more information please refer to
    https://www.microsoft.com/en-us/download/details.aspx?id=52531
    """

42
    def __init__(self):
43 44 45
        self.dataset_dir = os.path.join(DATA_HOME, "msra_ner")
        if not os.path.exists(self.dataset_dir):
            ret, tips, self.dataset_dir = default_downloader.download_file_and_uncompress(
Z
Zeyu Chen 已提交
46
                url=_DATA_URL, save_path=DATA_HOME, print_progress=True)
47 48
        else:
            logger.info("Dataset {} already cached.".format(self.dataset_dir))
49 50

        self._load_train_examples()
51 52
        self._load_test_examples()
        self._load_dev_examples()
53 54 55 56 57

    def _load_train_examples(self):
        train_file = os.path.join(self.dataset_dir, "train.tsv")
        self.train_examples = self._read_tsv(train_file)

58 59 60 61 62 63 64 65
    def _load_dev_examples(self):
        self.dev_file = os.path.join(self.dataset_dir, "dev.tsv")
        self.dev_examples = self._read_tsv(self.dev_file)

    def _load_test_examples(self):
        self.test_file = os.path.join(self.dataset_dir, "test.tsv")
        self.test_examples = self._read_tsv(self.test_file)

66 67 68
    def get_train_examples(self):
        return self.train_examples

69 70 71 72 73 74
    def get_dev_examples(self):
        return self.dev_examples

    def get_test_examples(self):
        return self.test_examples

75
    def get_labels(self):
76 77
        return ["B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "O"]

Z
Zeyu Chen 已提交
78 79 80 81 82 83 84
    @property
    def num_labels(self):
        """
        Return the number of labels in the dataset.
        """
        return len(self.get_labels())

85 86
    def get_label_map(self):
        return self.label_map
87

88 89
    def _read_tsv(self, input_file, quotechar=None):
        """Reads a tab separated value file."""
90
        with codecs.open(input_file, "r", encoding="UTF-8") as f:
91 92
            reader = csv.reader(f, delimiter="\t", quotechar=quotechar)
            examples = []
93 94
            seq_id = 0
            header = next(reader)  # skip header
95
            for line in reader:
96 97 98
                example = InputExample(
                    guid=seq_id, label=line[1], text_a=line[0])
                seq_id += 1
99 100 101 102 103 104 105 106
                examples.append(example)

            return examples


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