如何在Python中不使用正则表达式实现大小写不敏感的用户输入文本匹配
First, let's break down what was wrong with your original code:
- You reused
xas the loop variable, which overwrote your original search term (bad practice that breaks matching logic). - The condition
x.islower() or x.isupper() or x.capitalize()doesn't check for matches at all.x.capitalize()returns a non-empty string, which is always "truthy" in Python—so this condition just returned every word split from the text.
Here's the corrected code that does exactly what you need: finds all original words in the text that contain your search term (case-insensitive, no regex required):
# Get and clean the user's search input search_term = self.lineEditSearch.text().strip() # Handle empty input to avoid unexpected results if not search_term: self.varStr = [] print("No search term entered.") return # Read the file content text_content = self.ReadingFileContent(Item) # Split content into words (handles multiple spaces automatically) all_words = text_content.split() # Collect original words where search term is a substring (case-insensitive) self.varStr = [word for word in all_words if search_term.lower() in word.lower()] # Print the result to verify print(f"Matching words: {self.varStr}")
How this works:
- Case insensitivity: By converting both the search term and each word to lowercase with
.lower(), we eliminate case differences entirely. - Substring match: The
inoperator checks if the lowercase search term exists anywhere within the lowercase word (so "charl" will match "Charles", "charles", or "CHARLES"). - Preserves original words: We add the original word (with its original case and punctuation) to
self.varStr, not the lowercase version.
Example Output:
If your text contains "Les hiboux Charles Baudelaire ... Charles Pierre Baudelaire" and the user inputs "charl", self.varStr will be:
["Charles", "Charles"]
Optional: Handling Punctuation
If you want to ignore punctuation attached to words (like "établiront." or "méditent,"), you can modify the code to strip common punctuation first while keeping the original word in results:
import string # ... (previous code) # Strip punctuation from each word before checking, but retain original word in output self.varStr = [ word for word in all_words if search_term.lower() in word.strip(string.punctuation).lower() ]
This way, searching for "etabliront" will match "établiront." since we strip the period before checking, but the result still includes the original word "établiront.".
内容的提问来源于stack exchange,提问作者Propy Propy

