Нечеткий поиск Python

У меня есть большой образец текста, например:

«Артериальное высокое кровяное давление может влиять на прогноз выживания пациента в результате осложнений. ТЕНСТАТЕН вводится в рамках профилактического лечения. Его (ее, ее) отчет (отношение) эффективность / нежелательные эффекты важны. ... диуретики, препаратом первого назначения, которым является ТЕНСТАТЕН. Терапевтические альтернативы очень многочисленны».

И я пытаюсь определить, есть ли в тексте «задействовать прогноз выживания», но нечетко. Например, «имеет участие в прогнозе выживания» также должен возвращать положительный ответ.

Я изучил fuzzywuzzy, nltk и новые нечеткие функции регулярных выражений, но не нашел способа:

if [anything similar (>90%) to "that sentence"] in mybigtext:
    print True

person Mickael_Paris    schedule 29.02.2016    source источник
comment
Я новичок здесь, но я думаю, что это должно решить вашу проблему: stackoverflow.com/questions/30449452/   -  person Onikute Opeyemi O    schedule 29.02.2016
comment
Посмотрите gensim, особенно раздел сходства.   -  person Jan    schedule 29.02.2016


Ответы (3)


Следующее не идеально, но оно должно помочь вам начать. Он использует nltk, чтобы сначала разбить ваш текст на слова, а затем создает набор, содержащий основы всех слов, фильтруя любое стоп-слово. Он делает это как для вашего образца текста, так и для образца запроса.

Если пересечение двух наборов содержит все слова запроса, это считается совпадением.

import nltk

from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

stop_words = stopwords.words('english')
ps = PorterStemmer()

def get_word_set(text):
    return set(ps.stem(word) for word in word_tokenize(text) if word not in stop_words)

text1 = "The arterial high blood pressure may engage the prognosis for survival of the patient as a result of complications. TENSTATEN enters within the framework of a preventive treatment(processing). His(Her,Its) report(relationship) efficiency / effects unwanted is important. diuretics, medicine of first intention of which TENSTATEN, is. The therapeutic alternatives are very numerous."
text2 = "The arterial high blood pressure may engage the for survival of the patient as a result of complications. TENSTATEN enters within the framework of a preventive treatment(processing). His(Her,Its) report(relationship) efficiency / effects unwanted is important. diuretics, medicine of first intention of which TENSTATEN, is. The therapeutic alternatives are very numerous."

query = "engage the prognosis for survival"

set_query = get_word_set(query)
for text in [text1, text2]:
    set_text = get_word_set(text)
    intersection = set_query & set_text

    print "Query:", set_query
    print "Test:", set_text
    print "Intersection:", intersection
    print "Match:", len(intersection) == len(set_query)
    print

Сценарий предоставляет два текста, один проходит, а другой нет, он выводит следующий вывод, чтобы показать вам, что он делает:

Query: set([u'prognosi', u'engag', u'surviv'])
Test: set([u'medicin', u'prevent', u'effici', u'engag', u'Her', u'process', u'within', u'surviv', u'high', u'pressur', u'result', u'framework', u'diuret', u')', u'(', u',', u'/', u'.', u'numer', u'Hi', u'treatment', u'import', u'complic', u'altern', u'patient', u'relationship', u'may', u'arteri', u'effect', u'prognosi', u'intent', u'blood', u'report', u'The', u'TENSTATEN', u'unwant', u'It', u'therapeut', u'enter', u'first'])
Intersection: set([u'prognosi', u'engag', u'surviv'])
Match: True

Query: set([u'prognosi', u'engag', u'surviv'])
Test: set([u'medicin', u'prevent', u'effici', u'engag', u'Her', u'process', u'within', u'surviv', u'high', u'pressur', u'result', u'diuret', u')', u'(', u',', u'/', u'.', u'numer', u'Hi', u'treatment', u'import', u'complic', u'altern', u'patient', u'relationship', u'may', u'arteri', u'effect', u'framework', u'intent', u'blood', u'report', u'The', u'TENSTATEN', u'unwant', u'It', u'therapeut', u'enter', u'first'])
Intersection: set([u'engag', u'surviv'])
Match: False
person Martin Evans    schedule 29.02.2016
comment
Да, я думал о такой возможности! Если я действительно не могу найти никакого другого решения, я буду использовать его! Спасибо ! - person Mickael_Paris; 01.03.2016

Используя модуль regex, сначала разделите предложения, а затем проверьте, есть ли в предложении нечеткий шаблон:

tgt="The arterial high blood pressure may engage the prognosis for survival of the patient as a result of complications. TENSTATEN enters within the framework of a preventive treatment(processing). His(Her,Its) report(relationship) efficiency / effects unwanted is important. diuretics, medicine of first intention of which TENSTATEN, is. The therapeutic alternatives are very numerous."

for sentence in regex.split(r'(?<=[.?!;])\s+(?=\p{Lu})', tgt):
    pat=r'(?e)((?:has engage the progronosis of survival){e<%i})' 
    pat=pat % int(len(pat)/5)
    m=regex.search(pat, sentence)
    if m:
        print "'{}'\n\tfuzzy matches\n'{}'\n\twith \n{} substitutions, {} insertions, {} deletions".format(pat,m.group(1), *m.fuzzy_counts)

Отпечатки:

'(?e)((?:has engage the progronosis of survival){e<10})'
    fuzzy matches
'may engage the prognosis for survival'
    with 
3 substitutions, 1 insertions, 2 deletions
person dawg    schedule 29.02.2016
comment
Таким образом, играя с числами fuzzy_counts, например, ограничивая их ... я мог бы сделать что-то, чтобы определить разницу между: «задействовать прогноз» и «не использовать прогноз». Это кажется идеальным, спасибо! Я постараюсь показать свою проблему как решенную, если это так. - person Mickael_Paris; 02.03.2016

Ниже есть функция, которая, если слово содержится внутри текста, будет отображать совпадение. Вы можете импровизировать, чтобы заставить его проверять полные фразы в тексте.

Вот функция, которую я сделал:

def FuzzySearch(text, phrase):
    """Check if word in phrase is contained in text"""
    phrases = phrase.split(" ")

    for x in range(len(phrases)):
        if phrases[x] in text:
            print("Match! Found " + phrases[x] + " in text")
        else:
            continue
person Hazim Sager    schedule 29.02.2016