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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
|
import os import re import collections from nltk import word_tokenize, pos_tag from nltk.corpus import wordnet from nltk.stem import WordNetLemmatizer import jieba.analyse from tqdm import tqdm import random from rake_nltk import Rake from rake_nltk import Metric
result_number = 50
class extractKeyWords:
def __init__(self, save_path): ''' 初始化关键词提取器 :param save_path: 保存路径 ''' self.save_path = save_path self.sentences = [] words = [] stopwords = [] with open("./stopwords.txt" , "r", encoding="utf-8") as f: for line in f.readlines(): stopwords.append(line.strip()) print("Load Finish! Begin preprocess!") for ACL2020 in tqdm(os.listdir("./ACL2020_txt")): with open("./ACL2020_txt/" + ACL2020, 'r', encoding="utf-8") as f: for line in f.readlines(): line = line.lower() line = re.sub('[\W_]+', " ", line) line = re.sub('[0-9]', " ", line) line = re.sub(r'[\u4e00-\u9fa5]', "", line)
temp_words = word_tokenize(line) for word in temp_words: if word in stopwords: continue words.append(word) tags = pos_tag(words)
wnl = WordNetLemmatizer() lemmas_sent = [] for tag in tags: wordnet_pos = self._get_wordnet_pos(tag[1]) or wordnet.NOUN lemmas_sent.append(wnl.lemmatize(tag[0], pos=wordnet_pos)) self.sentences.append(" ".join(lemmas_sent)) print("preprocess finish!")
def _get_wordnet_pos(self, tag): ''' 根据tag来获取词性 :param tag: :return: ''' if tag.startswith('J'): return wordnet.ADJ elif tag.startswith('V'): return wordnet.VERB elif tag.startswith('N'): return wordnet.NOUN elif tag.startswith('R'): return wordnet.ADV else: return None
def run(self): self.method_1() self.method_2() self.method_3() self.method_4() self.method_5() self.method_6() self.method_7()
def method_1(self): ''' 使用权重 :return: ''' print("method1 begin!") sentences = [word_tokenize(sentences) for sentences in self.sentences] words = [] for sentence in sentences: for word in sentence: words.append(word) total = len(words) counter = collections.Counter(words) result = [] for temp in counter.most_common(result_number): temp = list(temp) temp[1] = temp[1]/total result.append(temp) self.write2file(result, "method1_dic.txt") print("method1 finish!")
def method_2(self): ''' 使用jieba分词的extract_tags的方法进行运算 :return: ''' print("method2 begin!") text = " ".join(self.sentences)
keywords = jieba.analyse.extract_tags(text, topK=result_number, withWeight=True, allowPOS=()) self.write2file(keywords, "method2_dic.txt") print("method2 finish!")
def method_3(self): ''' 使用随机的方法,随机选择result_number个关键词 :return: ''' print("method3 begin!") sentences = [word_tokenize(sentences) for sentences in self.sentences] words = [] for sentence in sentences: for word in sentence: words.append(word) total = len(words) numbers = [] while len(numbers) <= result_number: number = random.randint(0, total - 1) if number in numbers: continue numbers.append(number) counter = collections.Counter(words) result = [] for number in numbers: result.append([words[number], counter[words[number]] / total]) result.sort(key=lambda x: x[1], reverse=True) self.write2file(result, "method3_dic.txt") print("method3 finish!")
def method_4(self): ''' 使用jieba分词的tfidf方法获取关键词 :return: ''' print("method4 begin!") text = " ".join(self.sentences)
keywords = jieba.analyse.tfidf(text, topK=result_number, withWeight=True, allowPOS=()) self.write2file(keywords, "method4_dic.txt") print("method4 finish!")
def method_5(self): ''' 使用相对更加快速的rake算法,使用默认矩阵来进行关键词提取 :return: ''' print("method5 begin!") r = Rake(max_length = result_number) text = " ".join(self.sentences) r.extract_keywords_from_text(text)
keywords = r.get_ranked_phrases_with_scores()
result = [] head = [] for keyword in keywords: for word in keyword[1].split(" "): if(word in head): continue result.append([word, keyword[0]]) head.append(word) if(len(head) >= result_number): break if (len(head) >= result_number): break self.write2file(result, "method5_dic.txt") print("method5 finish!")
def method_6(self): ''' 使用相对更加快速的rake算法,使用词频矩阵来进行关键词提取 :return: ''' print("method6 begin!") r = Rake(max_length = result_number, ranking_metric = Metric.WORD_FREQUENCY) text = " ".join(self.sentences) r.extract_keywords_from_text(text)
keywords = r.get_ranked_phrases_with_scores()
result = [] head = [] for keyword in keywords: for word in keyword[1].split(" "): if(word in head): continue result.append([word, keyword[0]]) head.append(word) if(len(head) >= result_number): break if (len(head) >= result_number): break self.write2file(result, "method6_dic.txt") print("method6 finish!")
def method_7(self): ''' 使用相对更加快速的rake算法,使用词级矩阵来进行关键词提取 :return: ''' print("method6 begin!") r = Rake(max_length=result_number, ranking_metric=Metric.WORD_DEGREE) text = " ".join(self.sentences) r.extract_keywords_from_text(text)
keywords = r.get_ranked_phrases_with_scores()
result = [] head = [] for keyword in keywords: for word in keyword[1].split(" "): if (word in head): continue result.append([word, keyword[0]]) head.append(word) if (len(head) >= result_number): break if (len(head) >= result_number): break self.write2file(result, "method7_dic.txt") print("method7 finish!")
def write2file(self, keywords, save_path): ''' 将关键词刷新到指定文件中 :param keywords: (words, weight) 的列表 :param save_path: 保存的文件目录 :return: ''' with open(os.path.join(self.save_path, save_path), 'w', encoding="utf-8") as f: for keyword in keywords: f.write(str(keyword[0]) + "\t" + str(keyword[1]) + "\n")
if __name__ == '__main__': tmp = extractKeyWords("./result") tmp.run()
|