You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python字典中按部分文本搜索键并返回对应回复?

实现部分匹配并优化字典查询逻辑

Alright, let's tackle your problem step by step. You want to match partial strings against your msg column entries and return the corresponding reply, plus replace the defaultdict setup with a more flexible solution. Here's how to do it:

1. 核心思路:从精确匹配到部分匹配

Your original defaultdict approach only works for exact key matches, which is why searching for "Jeff" won't find "Jeff Bezos". Instead, we need to:

  • Filter out invalid rows (like those with NaN values) from your DataFrame first
  • Check each msg entry to see if it contains your search string
  • Return the corresponding reply if a match is found, or your error message if not

2. 替代defaultdict的优化方案:自定义匹配函数

A custom function is far more flexible than defaultdict here—it lets you adjust matching rules (like case insensitivity) and handle edge cases easily. Here's the implementation:

import pandas as pd

def get_reply(search_str, df):
    # Handle empty/invalid input from last_msg()
    if not search_str:
        return 'Error, input not valid'
    
    # Clean up the DataFrame: drop rows with empty msg or reply
    cleaned_df = df.dropna(subset=['msg', 'reply']).reset_index(drop=True)
    
    # Find rows where msg contains the search string (case-insensitive)
    matches = cleaned_df[cleaned_df['msg'].str.contains(search_str, case=False)]
    
    # Return result based on matches
    if not matches.empty:
        # Return the first matching reply; adjust if you need multiple results
        return matches.iloc[0]['reply']
    else:
        return 'Error, input not listed'

3. 整合到你的现有代码

Now replace your defaultdict setup with this function. Here's the full workflow:

# Load your data
df = pd.read_csv('MY_PATH')

# Your existing last_msg() function (with small improvements)
def last_msg():
    try:
        post = driver.find_elements_by_class_name("_12pGw")
        ultimo = len(post) - 1
        texto = post[ultimo].find_element_by_css_selector("span.selectable-text").text
        return texto.strip()  # Remove extra whitespace to avoid false negatives
    except Exception as e:
        print(f"Error extracting message: {e}")
        return None

# Get the search string and fetch the reply
search_text = last_msg()
response = get_reply(search_text, df)
print(response)

4. 额外优化选项

  • Case-sensitive matching: Remove the case=False parameter from str.contains() if you want exact case matches.
  • Full-word matching: If you want to match whole words only (e.g., "Jeff" won't match "Jeffrey"), use regex:
    import re
    matches = cleaned_df[cleaned_df['msg'].str.contains(r'\b' + re.escape(search_str) + r'\b', case=False)]
    
  • Return all matches: If multiple msg entries contain your search string, return a list of replies instead of the first one:
    return matches['reply'].tolist() if not matches.empty else 'Error, input not listed'
    

为什么这个方案更好?

  • Flexibility: You can tweak the matching logic without rewriting the entire lookup system.
  • Robustness: It handles empty inputs, NaN values, and extraction errors gracefully.
  • Readability: The function clearly states what it does, making it easier to maintain later.

内容的提问来源于stack exchange,提问作者guialmachado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:42:44