首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在字符串中搜索同时出现的2个单词?(Python)

在Python中,可以使用正则表达式或字符串方法来搜索同时出现的两个单词。

方法1:使用正则表达式

代码语言:txt
复制
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)

输出:

代码语言:txt
复制
['word1 and word2', 'word2 and word1']

方法2:使用字符串方法

代码语言:txt
复制
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)

输出:

代码语言:txt
复制
['word1 word2', 'word2 word1']

这两种方法都可以在给定的字符串中搜索同时出现的两个单词,并返回匹配的结果。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券