在Python中,可以使用字符串的find()
方法来查找包含给定词的特定句子。find()
方法返回匹配词的第一个字符索引,如果找不到匹配词则返回-1。
下面是一个示例代码,演示了如何在一段文本中查找包含给定词的特定句子:
def find_sentence_with_word(text, word):
sentences = text.split('.') # 假设句子以句号分隔
for sentence in sentences:
if word in sentence:
return sentence.strip() # 返回包含词的句子,并去除首尾空格
return None # 找不到匹配句子
text = "Hello, this is a sample text. It contains multiple sentences. Each sentence has different words."
word_to_find = "sample"
result = find_sentence_with_word(text, word_to_find)
if result:
print(f"Sentence with word '{word_to_find}': {result}")
else:
print(f"No sentence found with word '{word_to_find}'")
该代码会输出:
Sentence with word 'sample': Hello, this is a sample text
在这个示例中,find_sentence_with_word()
函数接受两个参数:文本和要查找的词。它首先将文本分割成句子,然后遍历每个句子来查找包含给定词的句子。如果找到匹配的句子,它将返回该句子,否则返回None
。
领取专属 10元无门槛券
手把手带您无忧上云