使用正则表达式从列表中抓取含listing关键词的元素
Got it, let's break down how to filter your list to get only the elements that include the "listing" keyword using Python's regex module.
Step 1: Import the Regex Module
First, we need to import re to work with regular expressions:
import re
Step 2: Define Your Original List
Let's start with the list you provided:
x = ['/category/Women-Dresses?size=0', '/brand/Free_People', '/closet/shopmyycloset', '/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', None, '#', '#', '#', '#', '#', None, ]
Step 3: Create the Regex Pattern and Filter the List
We'll use a regex pattern to detect the presence of "listing" in each string, and also skip non-string elements (like None in your list):
# Compile a regex pattern to look for the "listing" substring listing_pattern = re.compile(r'listing') # Filter the list: keep only strings that contain "listing" c = [item for item in x if isinstance(item, str) and listing_pattern.search(item)]
What This Does:
isinstance(item, str): Ensures we don't try to run regex checks onNoneor other non-string values (which would throw errors).listing_pattern.search(item): Checks if the substring "listing" exists anywhere in the string. If it does, the element is kept in the new listc.
Result
When you run this code, c will be exactly the target list you want:
print(c) # Output: # ['/listing/559c0800568c896f6e019f2a/unlike', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a', '/listing/Eyelet-drop-waist-dress-559c0800568c896f6e019f2a']
Optional: Strict Matching (If Needed)
If you want to only keep elements that start with /listing/ (instead of any string containing "listing"), you can adjust the regex pattern to:
listing_pattern = re.compile(r'^/listing/')
This ensures we only match URLs that begin with the /listing/ path segment, avoiding any accidental matches with "listing" in other parts of the string.
内容的提问来源于stack exchange,提问作者Bob

