Python находит ТОЛЬКО первый экземпляр слова в строке

#python #python-3.x #string #for-loop

#python #python-3.x #строка #for-цикл

Вопрос:

Новичок в Python здесь. Я хотел бы извлечь предложение, в котором был найден первый экземпляр слов в списке. В настоящее время он извлекает все строки, в которых есть слова ‘dog’ и ‘cat’. Я пытался (i.split('.')[0]) , но это тоже не работает. Кто-нибудь может помочь, пожалуйста?

 text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')

  

Вывод:

 the dog was there

the cat is there too

the dog want want want was there

na

  

Желаемый результат:

 the dog was there

the cat is there too

n/a (because choclate is not found)
  

Спасибо!

Ответ №1:

Без внесения большого количества изменений в ваш код, ваш результат может быть достигнут с помощью ‘remove’ в вашем списке ‘words’.

 text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for i in text.split('.'):
    for j in words:
        if j in i:
            print(i.split('.')[0])
            words.remove(j) # this will remove the matched element from your search list
            lst.append (i.split('.')[0]) 
else:
    lst.append('na')
    print('na')
  

Комментарии:

1. Спасибо! это изменяет порядок элементов в списке, возможно ли сохранить порядок?

2. Вы можете создать копию списка слов и работать с ним. Это в любом случае желательно, потому что remove изменяет ваш исходный список. Если все слова были найдены один раз, ваш список будет пуст в конце.

Ответ №2:

Если вы измените свои циклы, вы можете просто использовать break для перехода к следующему слову:

 text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for j in words: # each word
    for i in text.split('.'):  # each sentence
        if j in i:
            print(i.split('.')[0])
            lst.append (i.split('.')[0]) 
            break  # next word
else:
    lst.append('na')
    print('na')
  

Вывод:

 the dog was there
 the cat is there too
na
  

Комментарии:

1. Обращение циклов вспять также хорошо, потому что одно и то же предложение может быть первым, содержащим два разных слова — вы хотите иметь возможность вернуть его снова, и это сделает это.

Ответ №3:

Возможным решением может быть отслеживание того, какие слова вы нашли. Это может быть сделано следующим образом, если вы согласны с изменением words списка:

 text= 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '

lst=[]
words=['dog', 'cat', 'chocolate']
for sentence in text.split('.'):
    sentence = sentence.strip()  # Remove whitespace around sentence
    for word in words:
        if word in sentence:
            print(sentence)
            lst.append(sentence) 
            # Remove the found word from words
            words.remove(word)
else:
    lst.append('na')
    print('na')
  

Я также изменил имена некоторых переменных, чтобы сделать код более легко читаемым.
Этот фрагмент кода выводит следующее

 the dog was there
the cat is there too
na
  

Ответ №4:

Сокращая свой код (только на один цикл for), вы можете использовать pop() в списке word, чтобы удалить элемент оттуда:

 text = 'the dog was there. the cat is there too. python is the best. the dog want want want was there. '
sentences = text.split('.')
words=['dog', 'cat', 'chocolate']

for sentence in sentences:
    # Takes the first word as long as there are items in the list!
    word = words.pop(0) if words else None
    if word and word in sentence:
        print(sentence.strip())  # Removes whitespaces arround the sentence 
else:
    print('na')
  

Вывод:

 the dog was there
the cat is there too
na