如何让Python识别输入文本中所有"third-party"短语并输出上下文?
修改后的代码
# 导入colorama库 from colorama import init, Fore, Back, Style # 初始化colorama(解决部分终端颜色显示异常问题) init(autoreset=True) # 操作引导提示 print(Fore.GREEN + "\n复制你的用户协议内容") print("粘贴到搜索引擎的搜索框中") print("复制搜索框内的文本") entryPrompt = input("粘贴到这里:") # 将文本分割为单词列表 words = entryPrompt.split(" ") # 收集所有"third-party"出现的索引位置 matches = [idx for idx, word in enumerate(words) if word == "third-party"] if matches: print("\n") for i, pos in enumerate(matches, 1): # 计算上下文的起止索引,处理边界情况 start = max(0, pos - 20) end = min(len(words), pos + 21) # 切片左闭右开,+21才能包含目标词后20个单词 context = " ".join(words[start:end]) print(Fore.CYAN + f"第{i}处匹配的上下文:") print(f"...{context}...\n") else: print("\n") print(Fore.RED + "未找到第三方协议相关内容") print("\n") input("按回车键退出...")
关键修改说明
- 捕获所有匹配位置:替换仅返回首个匹配的
index()方法,用列表推导式结合enumerate()遍历单词列表,收集所有"third-party"的索引。 - 处理边界异常:计算上下文起始索引时用
max(0, pos-20)避免负索引,结束索引用min(len(words), pos+21)防止超出列表长度。 - 逐个输出结果:循环遍历所有匹配位置,为每个结果标注序号,清晰区分不同上下文片段。
- 优化颜色显示:添加
init(autoreset=True),无需手动重置颜色,简化代码逻辑。
内容的提问来源于stack exchange,提问作者Jams
相关产品推荐
相关产品推荐

