Python - Как найти одно или несколько слов в предложении - PullRequest
0 голосов
/ 19 ноября 2018

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

и т.д.

Sentence1 = "Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow"

Sentence2 = "Is it beautiful weather"

Sentence3 = "I hope it wont be snowing here soon"

Sentence4 = "How is the weather"

Words = ['I+be', 'it+weather']

Выход должен сказать

Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow

Is it beautiful weather

I hope it wont be snowing here soon

и причина, по которой он не печатает первый и последний, состоит в том, что он не содержит I и Be и it и погода

Так что мой вопрос в основном состоит в том, как сделать каждый + или любые другие специальные символы, такие как ключевое слово1 + ключевое слово2 + n (может быть от 1 до n слов), и сравнить, если эти слова присутствуют в предложении

То, что я пытался закодировать, было что-то вроде

Sentence = [
    "Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow",
    "Is it beautiful weather", "I hope it wont be snowing here soon",
    "How is the weather"]

Words = ['I', 'it+weather']

for loop_word in Words:
    for loop_setence in Sentence:
        if loop_word in loop_setence:
            print(loop_setence)
            break

Однако сейчас он выводит только первое предложение, поскольку я изменил слова на I на данный момент.

Что я хочу сделать, так это чтобы слова, содержащие более 1 слова, добавлялись со специальным символом между ними и т. Д. I + быть таким, чтобы всякий раз, когда в предложении присутствовали I и Be, он должен был печатать, что он нашел это предложение. - иначе ничего не печатать.

Illustration

Итак, мой вопрос к вам: как я могу продолжить с моей точки зрения со мной, желаю :)?

Ответы [ 2 ]

0 голосов
/ 19 ноября 2018

Использование filter, any, all и split

In [22]: Sentence1 = "Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow"
    ...:
    ...: Sentence2 = "Is it beautiful weather"
    ...:
    ...: Sentence3 = "I hope it wont be snowing here soon"
    ...:
    ...: Sentence4 = "How is the weather"
    ...:
    ...: Words = ['I+be', 'it+weather']
    ...:

In [23]: sentences = [Sentence1, Sentence2, Sentence3, Sentence4]

In [27]: list(filter(lambda s: any(all(w in s.split() for w in word.split('+')) for word in Words), sentences))
    ...:
Out[27]:
['Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow',
 'Is it beautiful weather',
 'I hope it wont be snowing here soon']

Понимание возвращает генератор True из False, если одно из ключевых слов находится в одномпредложений.all вернет True, если все элементы внутреннего контейнера равны True.И наоборот, any вернет True, если какие-либо элементы внутреннего контейнера True.

Проверка 'be' не возвращает Sentence2

In [43]: Words = ['be']

In [44]: list(filter(lambda s: any(all(w in s.split() for w in word.split('+')) for word in Words), sentences))
Out[44]:
['Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow',
 'I hope it wont be snowing here soon']

Примечаниечто это не будет учитывать пунктуацию.Т.е. 'Hello' != 'Hello,'

0 голосов
/ 19 ноября 2018

Вы можете сделать что-то вроде этого:

words = ['I+be', 'it+weather']
sentences = ["Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow",
             "Is it beautiful weather", "I hope it wont be snowing here soon", "How is the weather"]

def check_all(sentence, ws):
    return all(w in sentence for w in ws)

for sentence in sentences:
    if any(check_all(sentence, word.split('+')) for word in words):
        print(sentence)

Вывод

Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow
Is it beautiful weather
I hope it wont be snowing here soon

Функция check_all проверяет, все ли слова из группы слов(например 'I+be') в предложении.Затем, если для какой-либо группы слов есть в предложении, вы должны напечатать предложение.Обратите внимание, что сначала вы должны разбить на '+', чтобы найти, соответствует ли группа.

ОБНОВИТЬ

Чтобы соответствовать только целым словам, я предлагаю использовать regex , например:

import re

words = ['I+be', 'it+weather']
sentences = ["Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow",
             "Is it beautiful weather", "I hope it wont be snowing here soon", "How is the weather", "With In be"]


def check_all(sentence, ws):
    """Returns True if all the words are present in the sentence"""
    return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)


for sentence in sentences:
    if any(check_all(sentence, word.split('+')) for word in words):
        print(sentence)

Вывод

Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow
Is it beautiful weather
I hope it wont be snowing here soon

Обратите внимание, что второй пример не содержит "With In be" в выводе.

Далее

  1. См. Документацию по any и all .
  2. Регулярное выражение Pythonсоответствует целое слово
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...