使用Python pyahocorasick,搭配關鍵字,關鍵字大概在10-20個漢字之間。
建立ahocorasick的文本,是從本機檔案key_word的讀入。格式如下:
#母嬰專區<輔食<臉/麵條:嬰幼兒,幼兒,嬰兒,兒童,寶寶 | 麵條,細麵,粗麵,手工麵,蔬菜麵,營養麵,碎麵,掛麵,麵仔 |
####請有操作過這種問題的大大,幫忙看看,能提供範例程式碼,或提供處理思路,謝謝! ######import ahocorasick A = ahocorasick.Automaton() title = 'Hello Kitty3色蔬菜细面300克 婴儿幼儿营养面条宝宝辅食面条' with open('key_word', 'r') as f: for line in f.readlines(): line = line.strip() line = str(line.split('<')) A.add_word(line, line) A.make_automaton() aa = A.iter(title) for item in aa: print(item) # 打印为空值
仅有的幸福2017-05-18 10:49:50
研究了兩天,自己實現了這個功能
本地文件有太多重複關鍵字,匹配並不是100%,供參考
參考代碼如下:
import ahocorasick
A = ahocorasick.Automaton()
titles = ['Hello Kitty3色蔬菜细面300克 婴儿幼儿营养面条宝宝辅食面条']
word_dict = {}
with open('categories.csv', 'r') as f:
for line in f.readlines():
line = line.strip()
word_key = line.split(':')[0]
word_value = list(line.split(':')[1].split('|'))
word_dict[word_key] = word_value
line = (line.split(':')[1].split('|'))
for word in line:
if word == "":
continue
A.add_word(word, word)
A.make_automaton()
for title in titles:
category = []
aa = A.iter(title)
ret = []
matches = {}
for (k,v) in aa:
matches[v] = 1
for (k,v) in matches.items():
ret.append(k)
for value in word_dict.items():
if ret[0] in value[1]:
category.append(value[0]) #关键字太多,所以写死了一个keyword匹配的结果
#print(ret[0], value[0], value[1])
print(category[0])
印刷結果:母嬰專區<輔食<麵仔/麵條