Algorithm - python ahocorasick reads text from a local file and performs keyword matching, but the matching fails
迷茫
迷茫 2017-05-18 10:47:50
0
1
1012
  • 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!

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
仅有的幸福
  • 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!