如何在字符串矩阵中仅检索对话者A的奇数行内容并进行关键词搜索
Got it, let's walk through how to solve this problem step by step. Here's a straightforward way to run keyword searches only on Speaker A's lines (which you specified are the odd-numbered rows in your dialogue matrix):
Key Background Note
First, a quick clarification: in Python, lists are 0-indexed, so your "odd-numbered rows" (natural counting: 1st, 3rd, etc.) correspond to even indices (0, 2, 4...) in the array variable. We'll use this to target only Speaker A's content.
Method 1: Basic Existence Check
This function will return True if the keyword exists in any of Speaker A's lines, and False otherwise. We'll make it case-insensitive to avoid missing matches (e.g., "You" vs "you"):
array = [['hello', 'how', 'are', 'you'], ['I', 'am', 'doing', 'okay'], ['Okay', 'did','you', 'do', 'your', 'hw','?']] def search_speaker_a(keyword): # Extract only Speaker A's lines (step=2 skips even-indexed rows = Speaker B) speaker_a_lines = array[::2] # Check each line for the keyword (case-insensitive) for line in speaker_a_lines: if keyword.lower() in [word.lower() for word in line]: return True return False # Test it out! print(search_speaker_a("you")) # Returns True (found in both A lines) print(search_speaker_a("hw")) # Returns True (found in A's 3rd line) print(search_speaker_a("doing")) # Returns False (only in Speaker B's line)
Method 2: Detailed Match Results
If you want to get specific details about where the keyword was found (like which natural line number, the exact word, and full line content), use this version:
def search_speaker_a_detailed(keyword): speaker_a_lines = array[::2] matches = [] # Track natural line numbers (since Python uses 0-index, multiply by 2 and add 1) for idx, line in enumerate(speaker_a_lines): natural_line_num = idx * 2 + 1 # e.g., index 0 = natural line 1, index 2 = natural line 3 for word in line: if word.lower() == keyword.lower(): matches.append({ "natural_line": natural_line_num, "matched_word": word, "full_line": line }) return matches # Example usage print(search_speaker_a_detailed("you")) # Output: # [ # {'natural_line': 1, 'matched_word': 'you', 'full_line': ['hello', 'how', 'are', 'you']}, # {'natural_line': 3, 'matched_word': 'you', 'full_line': ['Okay', 'did', 'you', 'do', 'your', 'hw', '?']} # ]
Customization Tips
- Case-sensitive search: Remove the
.lower()calls from both the keyword and the words in the lines if you want exact case matches. - Partial matches: If you want to find words that contain the keyword (e.g., searching "do" and matching "did"), replace the equality check with
keyword.lower() in word.lower().
内容的提问来源于stack exchange,提问作者Roberto Guglielmo

