Fundamentals 5 min read

Detect Multiple Keywords in a Python String with Any, Regex, or Custom Functions

This article explains how to check whether a Python string contains any of several keywords—such as "宿舍", "公寓", or "酒店"—by presenting three practical solutions using the any() function, regular expressions, and a custom search function, complete with code examples.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Detect Multiple Keywords in a Python String with Any, Regex, or Custom Functions

Introduction

A fan asked how to determine if a string contains any of several keywords (e.g., "宿舍", "公寓", "酒店") and return 1 when a match is found.

Solution Overview

Three approaches are provided: using any(), using regular expressions, and using a custom function that returns 1.

Method 1 – any()

Using the built‑in any() function with a list comprehension:

s = '宿舍 饿了 酒店'
any([x in s for x in ['宿舍', '公寓', '酒店']])

Method 2 – Regular Expression

Leveraging re.search to match any of the keywords:

import re
text = '宿舍 饿了 酒店'
re.search('宿舍|公寓|酒店', text)

Method 3 – Custom Function Returning 1

# coding: utf-8
import re

def find_kw(text):
    kw = ['宿舍', '公寓', '酒店']
    for k in kw:
        f_t = re.search(k, text)  # Returns a match object if found
        if f_t:
            return 1

if __name__ == '__main__':
    text = '我住在希尔顿酒店'
    result = find_kw(text)
    if result:
        print(result)  # Prints 1 when a keyword is found

Conclusion

The three solutions demonstrate how to check for multiple keywords in a Python string using simple built‑in functions, regular expressions, or a custom function that returns a specific value. Feel free to adapt any method to your own projects.

Additional resources: https://github.com/cassieeric/Python-office-automation

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

anystring searchcustom-function
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.