Use Python pyahocorasick to match keywords, which are probably between 10-20 Chinese characters.
The text used to construct ahocorasick is read from the local file key_word. The format is as follows:
Maternal and infant area<Complementary food<Noodles/noodles: infants, toddlers, babies, children, babies | Noodles, thin noodles, thick noodles, handmade noodles, vegetable noodles, nutritious noodles, broken noodles, dried noodles, noodles |
The matching result is empty.
code show as below:
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) # 打印为空值
If anyone has experienced this kind of problem, please help, provide sample code, or provide solutions, thank you!
仅有的幸福2017-05-18 10:49:50
After two days of research, I implemented this function myself
The local file has too many repeated keywords and the matching is not 100%. For reference
The reference code is as follows:
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])
Print results: Mother and baby section<Complementary food<Noodles/Noodles