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

无需import实现查找目标单词各字符首次出现位置的Python代码需求

无导入Python跨行字符匹配功能实现

完整代码

lines = int(input())
phrases = []

for i in range(lines):
    phrase = str(input())
    # 移除指定标点和空格
    phrase = phrase.replace(',','')
    phrase = phrase.replace('!','')
    phrase = phrase.replace('.','')
    phrase = phrase.replace(';','')
    phrase = phrase.replace(':','')
    phrase = phrase.replace('?','')
    phrase = phrase.replace(' ','')
    # 统一转小写消除大小写影响
    phrase = phrase.lower()
    phrases.append(phrase)

# 目标单词同步转小写
word = str(input().strip().lower())

last_used_line = -1
match_result = []

for char in word:
    find_flag = False
    # 逐行查找,跳过上次使用的行
    for line_idx in range(len(phrases)):
        if line_idx == last_used_line:
            continue
        # 查找当前字符在该行的第一个出现位置
        char_pos = phrases[line_idx].find(char)
        if char_pos != -1:
            # 行号、字符位置统一转为1开头计数后记录
            match_result.append(f"{char}: word {line_idx + 1}, letter {char_pos + 1}")
            last_used_line = line_idx
            find_flag = True
            break
    if not find_flag:
        print("Word not founded")
        exit()

# 全部字符匹配成功输出结果
print("Word founded")
for res in match_result:
    print(res)

规则实现说明

  • 严格遵循相邻匹配字符不能出自同一行的要求,每次匹配自动跳过上次使用的行
  • 优先取每个字符符合行要求的最早出现位置,满足首次匹配的需求
  • 空行预处理后无有效字符,自动跳过不会被选中
  • 全流程大小写不敏感,所有输入内容统一转小写后再做匹配运算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 19:36:10