你可以使用Python的re模块来实现这个功能。下面是一个示例代码:
import re
def search_words(sentence, num_words):
pattern = r'\b\w+\b' # 匹配单词的正则表达式
words = re.findall(pattern, sentence) # 使用正则表达式在句子中找到所有的单词
filtered_words = []
if num_words == 'odd':
filtered_words = [word for i, word in enumerate(words) if i % 2 != 0]
elif num_words == 'even':
filtered_words = [word for i, word in enumerate(words) if i % 2 == 0]
return filtered_words
sentence = "Hello, how are you doing today?"
odd_words = search_words(sentence, 'odd')
even_words = search_words(sentence, 'even')
print("Odd Words:", odd_words)
print("Even Words:", even_words)
这个函数接受两个参数:句子和要搜索的单词数量。它使用正则表达式 \b\w+\b
匹配句子中的所有单词。然后根据给定的参数,选取奇数或偶数位置的单词,并将它们存储在一个列表中。最后,返回这个列表。
在上面的示例中,我们测试了句子 "Hello, how are you doing today?"。输出结果为:
Odd Words: ['how', 'you', 'today']
Even Words: ['Hello', 'are', 'doing']
这样,我们就找到了句子中的奇数和偶数个单词。