Удалить список фраз из строки - PullRequest
0 голосов
/ 18 июня 2020

У меня есть список фраз (н-граммов), которые нужно удалить из данного предложения.

    removed = ['range', 'drinks', 'food and drinks', 'summer drinks']
    sentence = 'Oranges are the main ingredient for a wide range of food and drinks'

Я хочу получить:

    new_sentence = 'Oranges are the main ingredient for a wide of'

Я пробовал Удалить список фраз из строки , но он не работает («Апельсины» превращаются в «О», «напитки» удаляются вместо фразы «еда и напитки»)

Кто-нибудь знаете как это решить? Спасибо!

Ответы [ 4 ]

1 голос
/ 18 июня 2020

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

>>> removed = ['range', 'drinks', 'food and drinks', 'summer drinks']
>>> sentence = 'Oranges are the main ingredient for a wide range of food and drinks'
>>> words = sentence.split()
>>> for ngram in sorted([r.split() for r in removed], key=len, reverse=True):
...     for i in range(len(words) - len(ngram)+1):
...         if words[i:i+len(ngram)] == ngram:
...             words = words[:i] + words[i+len(ngram):]
...             break
...
>>> " ".join(words)
'Oranges are the main ingredient for a wide of'

Обратите внимание, что есть несколько fl aws с этим простым подходом - несколько копий одной и той же n-граммы не будут удалены, но вы не можете продолжить с этим l oop после изменения words либо ( длина будет другой), поэтому, если вы хотите обрабатывать дубликаты, вам нужно будет пакетировать обновления.

0 голосов
/ 18 июня 2020
    import re

    removed = ['range', 'drinks', 'food and drinks', 'summer drinks']
    sentence = 'Oranges are the main ingredient for a wide range of food and drinks'

    # sort the removed tokens according to their length,
    removed = sorted(removed, key=len, reverse=True)

    # using word boundaries
    for r in removed:
        sentence = re.sub(r"\b{}\b".format(r), " ", sentence)

    # replace multiple whitspaces with a single one   
    sentence = re.sub(' +',' ',sentence)

Надеюсь, это поможет: сначала вам нужно отсортировать удаленные строки по их длине, таким образом, «еда и напитки» будут заменены на «напитки»

0 голосов
/ 18 июня 2020

Время регулярного выражения!

In [116]: removed = ['range', 'drinks', 'food and drinks', 'summer drinks']
     ...: removed = sorted(removed, key=len, reverse=True)
     ...: sentence = 'Oranges are the main ingredient for a wide range of food and drinks'
     ...: new_sentence = sentence
     ...: import re
     ...: removals = [r'\b' + phrase + r'\b' for phrase in removed]
     ...: for removal in removals:
     ...:     new_sentence = re.sub(removal, '', new_sentence)
     ...: new_sentence = ' '.join(new_sentence.split())
     ...: print(sentence)
     ...: print(new_sentence)
Oranges are the main ingredient for a wide range of food and drinks
Oranges are the main ingredient for a wide of
0 голосов
/ 18 июня 2020

Здесь вы go

removed = ['range', 'drinks', 'food and drinks', 'summer drinks','are']
sentence = 'Oranges are the main ingredient for a wide range of food and drinks'

words = sentence.split()
resultwords  = [word for word in words if word.lower() not in removed]
result = ' '.join(resultwords)
print(result)

Результаты:

Oranges the main ingredient for a wide of food and
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...