You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Python实现用户单词的词典变位词查询?含给定加载函数

Python变位词查询程序实现

没问题,我来帮你搞定这个变位词查询的程序。咱们核心思路很明确:变位词的字母排序后完全一致,而且得和输入单词长度相同(不过排序后长度必然一致,先过滤长度能提升查询效率)。下面是结合你提供的load函数实现的完整方案:

完整代码实现

import sys

def load(file):
    """Open a text file & turn contents into a list of lowercase strings."""
    try:
        with open(file) as in_file:
            loaded_txt = in_file.read().strip().split('\n')
            loaded_txt = [x.lower() for x in loaded_txt]
            return loaded_txt
    except IOError as e:
        print("{}\nError opening {}. Terminating program.".format(e, file), file=sys.stderr)
        sys.exit(1)

def find_anagrams(word_for_search, search_list_dictionary):
    """查找词典中与给定单词长度相同的变位词"""
    # 预处理目标单词:统一小写,排序字母作为匹配标识
    target_word = word_for_search.lower()
    target_sorted = sorted(target_word)
    target_length = len(target_word)
    
    matching_anagrams = []
    for word in search_list_dictionary:
        # 先跳过长度不同的单词,减少不必要的计算
        if len(word) != target_length:
            continue
        # 跳过单词本身(避免返回输入词自己)
        if word == target_word:
            continue
        # 排序当前单词字母,和目标标识对比
        if sorted(word) == target_sorted:
            matching_anagrams.append(word)
    
    return matching_anagrams

# 示例运行代码
if __name__ == "__main__":
    # 替换成你的词典文件路径,比如"english_dictionary.txt"
    dictionary_list = load("dictionary.txt")
    user_input = input("请输入一个单词:")
    results = find_anagrams(user_input, dictionary_list)
    
    if results:
        print(f"找到的变位词:{', '.join(results)}")
    else:
        print("没有找到匹配的变位词哦。")

关键逻辑说明

  • 前置过滤长度:先跳过和输入单词长度不同的词,避免对不可能匹配的单词做排序操作,提升查询速度。
  • 字母排序匹配:把单词的字母按顺序排列后,变位词的排序结果完全一致,这是判断变位词的核心依据。
  • 排除自身:如果词典里包含输入的单词本身,会自动跳过,避免结果里出现重复。

性能优化方案(针对大词典)

如果你的词典文件特别大,或者需要多次查询,建议提前把词典按“排序后的字母串”分组,这样后续查询可以直接取对应分组,不用每次遍历整个词典:

def build_anagram_lookup(dictionary):
    """提前构建变位词查找字典,提升多次查询的效率"""
    anagram_map = {}
    for word in dictionary:
        sorted_key = ''.join(sorted(word))
        if sorted_key not in anagram_map:
            anagram_map[sorted_key] = []
        anagram_map[sorted_key].append(word)
    return anagram_map

# 使用示例
if __name__ == "__main__":
    dictionary_list = load("dictionary.txt")
    lookup_dict = build_anagram_lookup(dictionary_list)
    
    user_input = input("请输入一个单词:")
    target_key = ''.join(sorted(user_input.lower()))
    # 从字典中取出所有匹配的词,排除自身
    results = [word for word in lookup_dict.get(target_key, []) if word != user_input.lower()]
    
    if results:
        print(f"找到的变位词:{', '.join(results)}")
    else:
        print("没有找到匹配的变位词哦。")

这种方式只需要在程序启动时构建一次查找字典,后续每次查询都是O(1)的时间复杂度,适合高频查询场景。

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

火山引擎 最新活动