在字符串中搜索单词/句子并打印以下单词

2024-09-29 07:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,大约有10行文字。我想做的是找到一个句子,其中有一个特定的词(s),并显示下面的词。你知道吗

字符串示例:

The quick brown fox

The slow donkey

The slobbery dog

The Furry Cat

我希望脚本搜索“the slow”,然后打印下面的单词,所以在本例中是“aduck”。你知道吗

我试过使用Find函数,但它只是打印单词的位置。你知道吗

示例代码:

 sSearch = output.find("destination-pattern")
        print(sSearch)

任何帮助都将不胜感激。你知道吗


Tags: the字符串示例quick单词句子文字slow
3条回答
output = "The slow donkey brown fox"
patt = "The slow"
sSearch = output.find(patt)
print(output[sSearch+len(patt)+1:].split(' ')[0])

输出:

donkey

我将使用正则表达式(re模块)按以下方式进行:

import re
txt = '''The quick brown fox
The slow donkey
The slobbery dog
The Furry Cat'''
words = re.findall(r'(?<=The slow) (\w*)',txt)
print(words) # prints ['donkey']

请注意,words现在是单词的list,如果您确定正好有一个单词可以找到,那么您可以执行以下操作:

word = words[0]
print(word) # prints donkey

说明:我在re.findall的第一个参数中使用了所谓的lookback断言,这意味着我在The slow后面寻找一些东西。\w*表示由字母、数字、下划线(_)组成的任何子串。我把它放在括号里,因为它不是单词的一部分。你知道吗

你可以用正则表达式。Python有一个名为re的内置库。你知道吗

用法示例:

s = "The slow donkey some more text"
finder = "The slow"
idx_finder_end = s.find(finder) + len(finder)
next_word_match = re.match(r"\s\w*\s", s[idx_finder_end:])
next_word = next_word_match.group().strip()
# donkey

相关问题 更多 >