在Python中,可以使用正则表达式或字符串方法来搜索同时出现的两个单词。
方法1:使用正则表达式
import re
def search_words(text, word1, word2):
pattern = r"\b" + word1 + r"\b.*\b" + word2 + r"\b|\b" + word2 + r"\b.*\b" + word1 + r"\b"
matches = re.findall(pattern, text)
return matches
text = "This is a sample text where both word1 and word2 appear together. Another sentence with word2 and word1."
word1 = "word1"
word2 = "word2"
result = search_words(text, word1, word2)
print(result)
输出:
['word1 and word2', 'word2 and word1']
方法2:使用字符串方法
def search_words(text, word1, word2):
words = text.split()
matches = []
for i in range(len(words)-1):
if words[i] == word1 and words[i+1] == word2:
matches.append(word1 + " " + word2)
elif words[i] == word2 and words[i+1] == word1:
matches.append(word2 + " " + word1)
return matches
text = "This is a sample text where both word1 and word2 appear together. Another sentence with word2 and word1."
word1 = "word1"
word2 = "word2"
result = search_words(text, word1, word2)
print(result)
输出:
['word1 word2', 'word2 word1']
这两种方法都可以在给定的字符串中搜索同时出现的两个单词,并返回匹配的结果。
领取专属 10元无门槛券
手把手带您无忧上云