Repository navigation
Expand file tree
/
Copy pathreader.py
More file actions
132 lines (109 loc) · 4.4 KB
/
Copy pathreader.py
File metadata and controls
132 lines (109 loc) · 4.4 KB
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
"""
Copyright (C) 2017-2020 Codebasic
Author: Lee Seongjoo <seongjoo@codebasic.io>
"""
import itertools
import abc
import reprlib
import re
from nltk.corpus import CorpusReader
from bs4 import BeautifulSoup
class TokenSeq(abc.ABC):
def __init__(self, fileids, encoding):
self.fileids = fileids
self.encoding = encoding
def __iter__(self):
return itertools.chain(
token for fid in self.fileids for token in self._get_token(fid) if token)
def __len__(self):
if not hasattr(self, 'length'):
self.length = 0
for _ in iter(self):
self.length += 1
return self.length
def __getitem__(self, index):
it = iter(self)
if isinstance(index, slice):
item_it = itertools.islice(it, index.start, index.stop, index.step)
return [token for token in item_it]
else:
item_it = itertools.islice(it, index, index+1)
return next(item_it)
def __repr__(self):
return reprlib.repr([token for token in itertools.islice(iter(self), 10)])
@abc.abstractmethod
def _get_token(self, fileid):
"""yield a token"""
class SejongCorpusReader(CorpusReader):
"""
Corpus reader for 세종 말뭉치 (Sejong Corpus)
"""
def __init__(self, root, fileids, encoding='utf-16'):
super().__init__(root, fileids, encoding)
def words(self, fileids=None, tagged=False, 형태분리=True):
"""
말뭉치로부터 토큰 획득
:param fileids: 말뭉치 파일 ID
:type fileids: list[str] or None
:return: 토큰 생성기
:rtype: generator
"""
return SejongWordSeq([fid for fid in self.abspaths(fileids)], encoding=self._encoding, tagged=tagged, 형태분리=형태분리)
def sents(self, fileids=None, tagged=False, 형태분리=False):
return SejongWordSeq([fid for fid in self.abspaths(fileids)], encoding=self._encoding, tagged=tagged, 형태분리=형태분리, sents=True)
class SejongWordSeq(TokenSeq):
def __init__(self, fileids, encoding, tagged, 형태분리, sents=False):
super().__init__(fileids, encoding)
self._tagged = tagged
self._형태분리 = 형태분리
self._sents = sents
def _get_token(self, fileid):
"""각 파일별 토큰 생성"""
soup = BeautifulSoup(open(fileid, encoding=self.encoding), 'lxml')
body = soup.find('text')
sent_elt = body.find_all(re.compile('^s$|^p$'))
for elt in sent_elt:
문장 = []
if elt.find('note'):
continue # skip <note>
for line in elt.text.split('\n'):
raw_token = line.split('\t')[-2:]
if not raw_token[-1]:
continue
token = raw_token[0]
# 어절이 없는 경우 확인
if not token:
continue
형태분석목록 = self._형태분석해독(raw_token)
# 형태 분석 결과가 없는 경우 확인
if not len(형태분석목록):
continue
if not self._sents:
if self._tagged:
yield (token, 형태분석목록)
else:
yield token
else: # 문장 단위인 경우
if self._tagged:
문장.append((token, 형태분석목록))
elif self._형태분리:
문장.extend(형태소 for 형태소, 품사 in 형태분석목록)
else:
문장.append(token)
yield 문장
def _형태분석해독(self, raw_token):
형태분석목록 = []
for tag in raw_token[-1].split('+'):
try:
형태소, _, 품사 = [원소 for 원소 in re.split('(/)', tag) if 원소]
except ValueError:
continue
else:
# 형태소 뒷번호 정리. 예: 세계__02 --> 세계
형태소 = re.sub(r'__\d{1,}', '', 형태소)
# 공백 제거
형태소 = 형태소.strip()
if not 형태소 or not 품사:
continue
형태분석목록.append((형태소, 품사))
return tuple(형태분석목록)