如何使用Python匹配用户输入与列表中的相似项?
Hey there! No need to apologize at all—we’ve all been stuck on small hurdles as Python newbies. Let’s walk through a few solid ways to solve your name matching problem, depending on what kind of "similarity" you’re looking for.
1. Basic Substring Matching (Case-Insensitive)
If you want to find names that contain the user’s input (even partially, and ignoring uppercase/lowercase differences), this simple approach works great:
names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] user_input = input('Enter name:').strip().lower() # Clean input and standardize case # Filter names where the input appears anywhere in the name (case-insensitive) matching_names = [name for name in names if user_input in name.lower()] if matching_names: print(f"Found matches: {', '.join(matching_names)}") else: print("No matching names found.")
strip()removes extra spaces from the user’s inputlower()ensures matches work regardless of capitalization (e.g., input "Ford" will catch both "tom ford" and "tim ford")
2. Fuzzy Matching (For Typos/Close Similarities)
If you want to account for small spelling mistakes (like "tim for" instead of "tim ford" or "shakespear" instead of "shakespeare"), Python’s built-in difflib library is perfect for this. It calculates similarity scores between strings:
import difflib names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] user_input = input('Enter name:').strip() # Get close matches (adjust cutoff to make matching stricter/looser) # cutoff = 0.0 is very loose, cutoff = 1.0 requires an exact match close_matches = difflib.get_close_matches(user_input, names, n=len(names), cutoff=0.6) if close_matches: print(f"Did you mean any of these? {', '.join(close_matches)}") else: print("No similar names found.")
n=len(names)ensures we return all possible matches, not just the top few- Tweak
cutoffbased on how strict you want the similarity check to be
3. Match by First/Last Name
If you want to specifically match by first name or last name (e.g., input "ford" should return both "tom ford" and "tim ford"), split each name into parts and check against the input:
names = ['william shakespeare', 'shakira', 'tom ford', 'tim ford'] user_input = input('Enter name:').strip().lower() matching_names = [] for name in names: name_parts = name.lower().split() # Check if input matches any part of the name, or the full name if user_input in name_parts or user_input in name.lower(): matching_names.append(name) if matching_names: print(f"Found matches: {', '.join(matching_names)}") else: print("No matching names found.")
内容的提问来源于stack exchange,提问作者Oscar Colón

