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

Python中如何检测字符串是否在列表中并从文本文件选取未使用的合规新词

Python单词接龙AI选词功能实现

现有代码存在以下问题:

  • 参数设计错误:仅传入历史单词列表,未传入已使用单词集合用于重复校验
  • 文件操作不规范:使用open()打开文件后未执行关闭操作,会造成文件资源泄漏
  • 逻辑流程错误:循环内第一次匹配失败就直接返回False,不会遍历剩余的单词条目
  • 校验条件缺失:缺少「目标单词未在已使用列表中出现」的核心校验逻辑
  • 返回值不符合需求:原需求是返回符合规则的新词,现有代码返回布尔值,完全不满足使用要求

按文件顺序选词实现

from typing import List

def ai_choice(used_words: List[str]) -> str | None:
    # 获取上一个单词的尾字母,统一转小写避免大小写匹配问题
    last_char = used_words[-1].strip().lower()[-1]
    # 已使用单词转小写集合,大幅提升查重效率
    used_set = {word.strip().lower() for word in used_words}
    
    # with语法自动管理文件生命周期,无需手动关闭
    with open('english3.txt', 'r', encoding='utf-8') as f:
        for line in f:
            current_word = line.strip().lower()
            # 过滤空行、校验首字母匹配+未被使用
            if current_word and current_word[0] == last_char and current_word not in used_set:
                return current_word
    # 无符合要求的单词时返回None,可用于触发游戏结束逻辑
    return None

随机选词实现(可选优化)

如果需要AI选词更灵活,不按文本固定顺序返回,可以使用以下版本:

import random
from typing import List

def ai_choice_random(used_words: List[str]) -> str | None:
    last_char = used_words[-1].strip().lower()[-1]
    used_set = {word.strip().lower() for word in used_words}
    valid_words = []
    
    with open('english3.txt', 'r', encoding='utf-8') as f:
        for line in f:
            current_word = line.strip().lower()
            if current_word and current_word[0] == last_char and current_word not in used_set:
                valid_words.append(current_word)
    
    return random.choice(valid_words) if valid_words else None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:36:04