繁体   English   中英

Python 仅查找字符串中单词的第一个实例

[英]Python find ONLY the first instance of a word in a string

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)

谢谢你!

无需对代码进行大量更改,即可通过在“单词”列表中使用“删除”来实现输出。

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')

如果您反转循环,则可以使用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

一个可能的解决方案可能是跟踪您找到了哪些单词。 如果您可以修改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

缩小你的代码(只有一个 for 循环),你可以在单词列表上使用pop()从那里删除一个项目:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM