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

如何使用Python检测文本文件内容是否已按字母顺序排序

用Python检测文件是否按字母顺序排序的方法

我来给你分享几种实用的方法,你可以根据自己的需求来选择:

基础版:严格按字符串ASCII顺序检测

这个方法会严格按照字符串的ASCII值来比较,区分大小写和行内的空格,适合需要精确匹配排序规则的场景。

def is_file_sorted(file_path):
    # 读取文件所有行,保留行内内容,只去掉末尾换行符
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = [line.rstrip('\n') for line in f]
    
    # 遍历相邻行,检查是否前一行 <= 后一行
    for i in range(len(lines) - 1):
        if lines[i] > lines[i+1]:
            return False
    return True

# 测试你的input.txt文件
print(is_file_sorted('input.txt'))

针对你给出的input.txt内容:

A story book is on table
By the river, there is a duck
Meanwhile, let's cooking

这个方法会返回True,因为按ASCII顺序,"A..." < "By..." < "Meanwhile..."是成立的。

进阶版:忽略大小写的检测

如果你的排序需求是不区分大小写(比如自然语言的字母排序),可以把每行转成小写后再比较:

def is_file_sorted_case_insensitive(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        # 转小写并去掉换行符
        lines = [line.rstrip('\n').lower() for line in f]
    
    for i in range(len(lines) - 1):
        if lines[i] > lines[i+1]:
            return False
    return True

print(is_file_sorted_case_insensitive('input.txt'))

比如如果文件里有"apple"和"Banana",基础版会认为"Banana"更小(因为大写B的ASCII值比小写a小),而这个版本会正确判断"apple" < "banana"。

高级版:忽略空格和大小写,过滤空行

如果文件里有行首行尾的空格,或者空行,这个方法可以处理得更干净:

def is_file_sorted_clean(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        # 去掉行首行尾空格、转小写,同时过滤空行
        lines = [line.strip().lower() for line in f if line.strip()]
    
    for i in range(len(lines) - 1):
        if lines[i] > lines[i+1]:
            return False
    return True

print(is_file_sorted_clean('input.txt'))

这个版本会自动跳过空行,并且不会因为行首的空格影响排序判断,适合处理格式不太规整的文本文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:05:17