第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")
相关推荐
我狸才不是赔钱货3 小时前
Python的“环境之殇”:从Venv到Conda的终极抉择
开发语言·python·conda
程序员爱钓鱼4 小时前
Python编程实战 - 函数与模块化编程 - 参数与返回值
后端·python·ipython
程序员爱钓鱼4 小时前
Python编程实战 - 函数与模块化编程 - 局部变量与全局变量
后端·python·ipython
jiuri_12159 小时前
Docker使用详解:在ARM64嵌入式环境部署Python应用
python·docker·容器
chenchihwen9 小时前
AI代码开发宝库系列:Function Call
人工智能·python·1024程序员节·dashscope
汤姆yu11 小时前
基于python的化妆品销售分析系统
开发语言·python·化妆品销售分析
上去我就QWER11 小时前
Python下常用开源库
python·1024程序员节
程序员杰哥13 小时前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
Jyywww12113 小时前
Python基于实战练习的知识点回顾
开发语言·python