第1个小脚本:英语单语按字母个数进行升序排序

单词来源于coca单词库

效果如下:

2个字母的单词

3个字母的单词

4个字母的单词

5个字母的单词

...

n个字母的单词

bash 复制代码
def sort_words_by_length_and_alphabet(text):
    # 将输入文本按空格分割为单词列表
    words = text.split()

    # 去除标点符号
    import string
    words = [word.translate(str.maketrans('', '', string.punctuation)) for word in words]

    # 去掉重复的单词
    unique_words = set(words)
    #将所有单词转换为小写字母
    unique_words = [word.lower() for word in unique_words]

    # 按照每个单词的长度和字母顺序进行排序
    sorted_words = sorted(unique_words, key=lambda word: (len(word), word))

    # 返回排序后的单词列表
    return sorted_words


# 示例用法
if __name__ == "__main__":
    # 读取文件内容
    with open('COCA_20000.txt', 'r', encoding='utf-8') as file:
        text = file.read()

    # 提取单词并排序
    sorted_words = sort_words_by_length_and_alphabet(text)
    print("按单词长度和字母顺序升序排序的结果:", sorted_words)

    # 保存到文件
    with open('sorted_words.txt', 'w', encoding='utf-8') as file:
        for word in sorted_words:
            file.write(word + '\n')
    print("已保存到文件 sorted_words.txt")
相关推荐
ZTLJQ2 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
H5css�海秀3 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---3 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
无敌昊哥战神3 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
李昊哲小课5 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_894241925 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
Zzzz_my6 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭7 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2147 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197738 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python