-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_segment.py
More file actions
72 lines (61 loc) · 2.14 KB
/
word_segment.py
File metadata and controls
72 lines (61 loc) · 2.14 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
# -*- coding: utf-8 -*-
# word_segment.py用于语料分词
import logging
import os.path
import sys
import re
import jieba
# 先用正则将<content>和</content>去掉
def reTest(content):
reContent = re.sub('<content>|</content>','',content)
return reContent
def loadStopWords(filepath):
stopwords = [line.strip() for line in open(filepath,'r',encoding="utf-8").readlines()]
return stopwords
def removeStopWords(sentence):
stopwords = loadStopWords('D:/Topic/code/segment/stop_words.txt')
output = ''
sentence_seg = jieba.cut(sentence)
for word in sentence_seg:
if word not in stopwords:
output += word
output += " "
return output
if __name__ == '__main__':
program = os.path.basename(sys.argv[0])
logger = logging.getLogger(program)
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
logging.root.setLevel(level=logging.INFO)
logger.info("running %s" % ' '.join(sys.argv))
# check and process input arguments
#if len(sys.argv) < 3:
# print (globals()['__doc__'] % locals())
#sys.exit(1)
#inp, outp = sys.argv[1:3]
#inp = "corpus.txt"
outp = "output_4_category.txt"
rootdir = "D:/Topic/code/segment/data/word2vec_data/articles"
space = " "
i = 0
r = '[,。:?“”!、()《》’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]+'
foutput = open(outp,'a',encoding='utf-8')
count = 0
for root, dirs, files in os.walk(rootdir):
#finput = open (str(filenames),"r",encoding='utf-8')
for folder in dirs:
for root, dirs, files in os.walk(rootdir+'/'+ folder):
for file in files:
finput = open (os.path.join(root,file),"r",encoding='utf-8')
for line in finput:
line = re.sub(r,' ',line.strip())
#line_seg = removeStopWords(jieba.cut(line))
line_seg = removeStopWords(line)
#foutput.write(space.join(line_seg))
foutput.write(line_seg)
i = i + 1
if (i % 1000 == 0):
logger.info("Saved " + str(i) + " articles_seg")
foutput.write('\n')
finput.close()
logger.info("Finished Saved " + str(i) + " articles")
foutput.close()