Python词搜索功能开发:保留匹配单词其余字符替换为感叹号及报错修复
Python词搜索代码实现方案
原有代码问题排查
首先你遇到的list index out of range报错核心原因和其他隐藏问题如下:
- 变量逻辑完全混乱:你把目标单词
word和网格的行列属性搞反了,b = len(word[0])是取单词第一个字符的长度,恒等于1,后续循环范围完全不符合网格实际大小,直接触发索引越界 - 操作逻辑错误:你直接用写模式打开原测试文件,会直接覆盖原始网格数据,导致后续匹配无数据源可用
- 功能逻辑缺失:完全没有实现对角线、水平、垂直方向的正逆序匹配逻辑,匹配判断规则不成立
- 输出规则不符合需求
可直接运行的修复后代码
def word_search(): # 读取文件和目标词 filename = input("Enter name of test file:") target = input("What word are you searching: ").strip() # 只读模式读取网格,去除每行末尾的换行符 with open(filename, 'r', encoding='utf-8') as f: grid = [line.rstrip('\n') for line in f.readlines()] if not grid or not target: print("I can't find this word.") return rows = len(grid) cols = len(grid[0]) target_len = len(target) # 8个搜索方向:水平左右、垂直上下、四个对角线方向 directions = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)] # 存储匹配到的字符坐标 matched_pos = set() found = False # 遍历每个网格点作为搜索起点 for i in range(rows): for j in range(cols): # 遍历每个搜索方向 for dx, dy in directions: # 计算当前方向下的终点坐标,判断是否超出网格范围 end_x = i + (target_len - 1)*dx end_y = j + (target_len - 1)*dy if end_x < 0 or end_x >= rows or end_y <0 or end_y >= cols: continue # 拼接当前方向下的连续字符串 current_str = '' temp_pos = [] for k in range(target_len): x = i + k*dx y = j + k*dy current_str += grid[x][y] temp_pos.append((x,y)) # 匹配正序或者逆序目标词 if current_str == target or current_str[::-1] == target: found = True matched_pos.update(temp_pos) if not found: print("I can't find this word.") return # 生成输出网格,非匹配位置替换为感叹号 for x in range(rows): output_line = [] for y in range(len(grid[x])): if (x,y) in matched_pos: output_line.append(grid[x][y]) else: output_line.append('!') print(''.join(output_line)) word_search()
功能验证说明
代码完全符合需求:
- 支持水平、垂直、对角线共8个方向的正序、逆序单词匹配
- 匹配到单词后仅保留对应位置的原字符,其余全部替换为感叹号输出
- 测试用例输入目标词
sweetfoodislife时,会输出你提供的预期结果
内容的提问来源于stack exchange,提问作者JJJ
相关产品推荐
相关产品推荐

