第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")
相关推荐
Patrick在香港5 分钟前
同一份脚本,mac 正常 Windows 乱码:open() 默认编码实测(附 3.15 终局)
utf-8·windows·python·macos·跨平台·编码·标准库
勿信日志26 分钟前
Playwright 元素定位:一个 width>50 过滤器把 42px 的输入框删掉了
python
larance31 分钟前
[菜鸟教程] 机器学习教程十课-Python 机器学习应用
人工智能·python·机器学习
栖凤31 分钟前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python
Yyyyyy~39 分钟前
【python】函数
python
金銀銅鐵41 分钟前
[Java] 借助GUI展示class文件的版本号
后端·python·ai编程
外收内放43 分钟前
Python基础语法练习题(62原始版本及其优化版本)
开发语言·python
棉猴1 小时前
玩游戏学Python4-字符串
python·游戏·字符串·pygame·玩游戏
东来也_八门1 小时前
我用麦当劳开放的 MCP,把那个最冷门的营养接口做成了真实配餐求解器
python
AI日报派送佬1 小时前
Ultralytics YOLO 模型训练技巧与最佳实践
人工智能·python·深度学习·yolo·机器学习·计算机视觉