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

如何用Python处理文本文件:筛选7字母词并匹配字母子集变位词

问题描述

我有一个包含2-7个字母单词的文本文件,需要完成以下操作:

  1. 生成仅包含所有7字母单词的子列表;
  2. 针对每个7字母单词W,列出原列表中所有属于W字母任意子集的变位词(包括W本身),并按单词长度从短到长排序;
  3. 将步骤2的结果保存到新文件中。

示例

输入文件中的原始单词列表

peaty
meant
eat
payment
motion
emotion
no
novel
inlet
violet
violent

期望结果

列表中的7字母单词为payment、emotion和violent。

预期输出文件内容

eat|peaty|meant|payment 
no|motion|emotion
no|novel|inlet|violet|violent

现有代码

我已经完成了提取7字母单词的部分代码:

with open('list1.txt', 'r') as f1, open('newlist.txt', 'w') as f2:
   for line in f1:
       if len(line) <9:
            f2.write(line)

但不知道后续如何实现,请问有人能提供解决方案吗?


解决方案

通过字母计数对比可以高效判断单词是否属于目标7字母单词的字母子集,再按要求排序输出。以下是完整实现代码:

from collections import Counter

def get_char_count(word):
    # 生成按a-z顺序排列的字母计数元组,用于快速对比
    count = Counter(word)
    return tuple(count.get(chr(ord('a') + i), 0) for i in range(26))

def main():
    # 读取原始文件,清理换行符并过滤空行
    with open('list1.txt', 'r') as f:
        all_words = [line.strip() for line in f if line.strip()]

    # 筛选所有7字母单词
    seven_letter_words = [word for word in all_words if len(word) == 7]

    # 预处理所有单词的字母计数特征
    word_counts = {word: get_char_count(word) for word in all_words}

    output_lines = []
    for target_word in seven_letter_words:
        target_count = word_counts[target_word]
        matched_words = []
        # 遍历所有单词,筛选符合条件的条目
        for word in all_words:
            word_count = word_counts[word]
            valid = True
            # 逐个字母对比计数,确保单词字母不超出目标单词的字母范围和数量
            for w_cnt, t_cnt in zip(word_count, target_count):
                if w_cnt > t_cnt:
                    valid = False
                    break
            if valid:
                matched_words.append(word)
        # 按单词长度从小到大排序,同长度单词保持原列表顺序
        matched_words.sort(key=lambda x: len(x))
        output_lines.append('|'.join(matched_words))

    # 将结果写入文件
    with open('result.txt', 'w') as f:
        f.write('\n'.join(output_lines))

if __name__ == "__main__":
    main()

代码说明

  • get_char_count函数:把单词转换为标准化的字母计数元组,比如eat会转为(1,0,0,...,1,0,...,1,0...)(a、e、t对应位置为1,其余为0),让字母数量对比更高效。
  • 读取单词时过滤空行,避免无效数据干扰。
  • 筛选匹配单词时,通过逐个字母的计数对比,确保目标单词的字母完全覆盖当前单词的字母需求。
  • 排序采用稳定排序规则,长度相同的单词会保留原始列表中的出现顺序,和示例输出一致。

执行代码后,result.txt的内容会与预期输出完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:20:21