File size: 5,585 Bytes
06124c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
from pathlib import Path
import re
import shutil
import string

import pandas as pd
from tqdm import tqdm

from project_settings import project_path


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--data_dir",
        default=(project_path / "data").as_posix(),
        type=str
    )
    parser.add_argument(
        "--output_file",
        default="metadata.csv",
        type=str
    )
    args = parser.parse_args()
    return args


class RepeatReplacer(object):
    def __init__(self, repeat_regexp: str = '(\\w*)(\\w)\\2(\\w*)', repl: str = '\\1\\2\\3'):
        self.repeat_regexp = re.compile(repeat_regexp)
        self.repl = repl

    def replace(self, word: str):
        repl_word = self.repeat_regexp.sub(self.repl, word)
        if repl_word != word:
            return self.replace(repl_word)
        else:
            return repl_word


class FilenamePreprocess(object):
    def __init__(self):
        self.punctuation_map = {
            ",": ",",
            "。": "",
            ".": "",
            "、": ",",
            "?": "",
            "?": "",
            ":": "",
            ":": "",
            "/": "_",
            "<": "",
            ">": "",
            "{": "{",
            "}": "}",
            "(": "(",
            ")": ")",
            "【": "(",
            "】": ")",
            "「": "\'",
            "」": "\'",
            "『": "\'",
            "』": "\'",
            "《": "(",
            "》": ")",
            "”": "\'",
            "“": "\'",
            "‘": "\'",
            "’": "\'",
            "…": "-",
            "=": "",

            "^_^": "",
            "◆": "",
            "☆": "",
            "...": "",

            "": "",
            " ": "",
            " ": "",
            "\t": "",
            "\n": "",
            "\r": "",
            "\v": "",
            "\f": "",

        }

        self.rstrip_char = list("(_-")

        self.pattern_map = {
            # r"-+": "-",
            # r"!+": "!",
        }

        self.repeat_replacer = RepeatReplacer(
            repeat_regexp='(\\w*)([-!…])\\2(\\w*)',
            repl='\\1\\2\\3',
        )

    def char_b2q(self, uchar):
        """单个字符 半角转全角"""
        inside_code = ord(uchar)
        if inside_code < 0x0020 or inside_code > 0x7e:
            return uchar
        if inside_code == 0x0020:
            inside_code = 0x3000
        else:
            inside_code += 0xfee0
        return chr(inside_code)

    def char_q2b(self, uchar):
        """单个字符 全角转半角"""
        inside_code = ord(uchar)
        if inside_code == 0x3000:
            inside_code = 0x0020
        else:
            inside_code -= 0xfee0
        if inside_code < 0x0020 or inside_code > 0x7e:
            return uchar
        return chr(inside_code)

    def q2b(self, text: str):
        """全角转半角"""
        result = ""
        for c in text:
            c = self.char_q2b(c)
            result += c
        return result

    def remove_space(self, text: str):
        text = text.replace(" ", "")
        return text

    def replace_punctuation(self, text: str):
        for k, v in self.punctuation_map.items():
            text = text.replace(k, v)
        return text

    def replace_by_pattern(self, text: str):
        for k, v in self.pattern_map.items():
            text = re.sub(k, v, text)
        return text

    def replace_repeat(self, text: str):
        text = self.repeat_replacer.replace(text)
        return text

    def strip_brackets(self, text: str):
        text_ = text
        if text_.startswith("("):
            text_ = text_.replace("(", "", 1)
            text_ = text_.replace(")", "", 1)
        if text_.startswith("《"):
            text_ = text_.replace("《", "", 1)
            text_ = text_.replace("》", "", 1)
        if text_.startswith("("):
            text_ = text_.replace("(", "", 1)
            text_ = text_.replace(")", "", 1)
        if text_.startswith("【"):
            text_ = text_.replace("【", "", 1)
            text_ = text_.replace("】", "", 1)

        if text_ != text:
            text_ = self.strip_brackets(text_)
        return text_

    def rstrip(self, text: str):
        for c in self.rstrip_char:
            text = text.rstrip(c)
        return text

    def process(self, text: str):
        # print(text)

        text = self.q2b(text)
        text = self.strip_brackets(text)
        text = self.replace_punctuation(text)
        text = self.replace_by_pattern(text)
        text = self.replace_repeat(text)

        text = self.rstrip(text)

        # print(text)
        return text


def main():
    args = get_args()

    data_dir = Path(args.data_dir)
    filename_list = data_dir.glob("*/*.txt")

    fn_preprocess = FilenamePreprocess()

    result = list()
    for filename in tqdm(filename_list):
        name = filename.stem
        splits = name.split("_")
        idx = splits[-1]
        novel_name = "_".join(splits[:-1])

        new_novel_name = fn_preprocess.process(novel_name)

        new_filename = filename.parent / "{}_{}.txt".format(new_novel_name, idx)
        new_filename = new_filename.as_posix().replace("/data/", "/data/")
        new_filename = Path(new_filename)
        new_filename.parent.mkdir(parents=True, exist_ok=True)

        shutil.move(filename.as_posix(), new_filename.as_posix())

    return


if __name__ == '__main__':
    main()