大文字小文字を区別しない検索関数の作成
大文字小文字を区別しない比較のさまざまな方法を学んだところで、大文字小文字に関係なくテキスト内の単語を見つける実用的な検索関数を作成しましょう。
検索関数の作成
- WebIDE で新しいファイルを作成し、
search_function.py と名付けます。
- 以下のコードを追加して、シンプルな大文字小文字を区別しない検索関数を実装します。
def search_text(query, text):
"""
Search for a query in text, ignoring case.
Returns a list of all matching positions.
"""
## Convert both to lowercase for case-insensitive comparison
query_lower = query.lower()
text_lower = text.lower()
found_positions = []
position = 0
## Find all occurrences
while position < len(text_lower):
position = text_lower.find(query_lower, position)
if position == -1: ## No more matches
break
found_positions.append(position)
position += 1 ## Move to the next character
return found_positions
## Example text
sample_text = """
Python is a programming language that lets you work quickly and integrate systems effectively.
python is easy to learn, powerful, and versatile.
Many developers love PYTHON for its simplicity and readability.
"""
## Test search
search_query = "python"
results = search_text(search_query, sample_text)
## Display results
if results:
print(f"Found '{search_query}' at {len(results)} positions: {results}")
## Show each match in context
print("\nMatches in context:")
for pos in results:
## Get some context around the match (10 characters before and after)
start = max(0, pos - 10)
end = min(len(sample_text), pos + len(search_query) + 10)
context = sample_text[start:end]
## Highlight the match by showing the original case from the text
match_original_case = sample_text[pos:pos+len(search_query)]
print(f"...{context.replace(match_original_case, f'[{match_original_case}]')}...")
else:
print(f"No matches found for '{search_query}'")
- ファイルを保存し、以下のコマンドで実行します。
python3 search_function.py
以下のような出力が表示されるはずです。
Found 'python' at 3 positions: [1, 67, 132]
Matches in context:
...[Python] is a pro...
...ctively.
[python] is easy ...
...ers love [PYTHON] for its ...
これは、関数が "Python"、"python"、"PYTHON" と書かれているかに関係なく、3 箇所で "Python" を見つけたことを示しています。また、関数は各マッチを元の文脈で表示し、元の大文字小文字を保持しています。
検索関数の拡張
関数を拡張して、単語のカウントと完全一致のオプションを追加し、より便利なものにしましょう。
search_function.py ファイルに以下のコードを追加します。
def count_word_occurrences(word, text, whole_word=False):
"""
Count occurrences of a word in text, ignoring case.
If whole_word=True, only count complete word matches.
"""
word_lower = word.lower()
text_lower = text.lower()
if whole_word:
## Use word boundaries to match whole words only
import re
pattern = r'\b' + re.escape(word_lower) + r'\b'
matches = re.findall(pattern, text_lower)
return len(matches)
else:
## Simple substring counting
return text_lower.count(word_lower)
## Test the enhanced function
test_text = """
Python is great. I love python programming.
This python-script demonstrates case-insensitive searching.
The word "python" appears multiple times as a whole word and as part of other words.
"""
## Count all occurrences (including within words)
count_all = count_word_occurrences("python", test_text)
print(f"Total occurrences of 'python' (including within words): {count_all}")
## Count only whole word occurrences
count_whole = count_word_occurrences("python", test_text, whole_word=True)
print(f"Whole word occurrences of 'python': {count_whole}")
スクリプトを再度実行します。
python3 search_function.py
以下の追加の出力が表示されるはずです。
Total occurrences of 'python' (including within words): 4
Whole word occurrences of 'python': 3
これは、"python" が合計 4 回出現するが、完全な単語としては 3 回しか出現しないことを示しています(1 回は "python-script" の中にあり、完全な単語とは一致しません)。
さまざまなシナリオのテスト
関数がさまざまなタイプのテキストをどのように処理するかを示すために、もう 1 つのテストを追加しましょう。
## Add more test cases
test_cases = [
("Python programming is fun", "python", "Simple sentence with one occurrence"),
("Python, python, PYTHON!", "python", "Multiple occurrences with different cases"),
("No matches here", "python", "No matches"),
("Python-script and PythonProgram contain python", "python", "Mixed word boundaries")
]
print("\nTesting different scenarios:")
for text, search_word, description in test_cases:
whole_matches = count_word_occurrences(search_word, text, whole_word=True)
all_matches = count_word_occurrences(search_word, text)
print(f"\nScenario: {description}")
print(f"Text: '{text}'")
print(f" - Whole word matches: {whole_matches}")
print(f" - All matches: {all_matches}")
このコードを追加し、スクリプトを再度実行します。
python3 search_function.py
関数がさまざまなテキストシナリオをどのように処理するかの詳細な内訳が表示されます。
Testing different scenarios:
Scenario: Simple sentence with one occurrence
Text: 'Python programming is fun'
- Whole word matches: 1
- All matches: 1
Scenario: Multiple occurrences with different cases
Text: 'Python, python, PYTHON!'
- Whole word matches: 3
- All matches: 3
Scenario: No matches
Text: 'No matches here'
- Whole word matches: 0
- All matches: 0
Scenario: Mixed word boundaries
Text: 'Python-script and PythonProgram contain python'
- Whole word matches: 1
- All matches: 3
これは、大文字小文字を区別しない比較が実世界の検索関数でどのように使用できるか、およびさまざまな検索要件を処理するオプションを持つことを示しています。
次のステップでは、これらの技術を適用して、実用的なユーザー入力検証アプリケーションを作成します。