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

Python实现文件单词去重并按sort()规则排序问题求助

Python实现无重复单词排序列表

需求说明

  • 逐行读取文件内容
  • 用split()将每行拆分为单词列表
  • 构建无重复的单词列表(每个单词仅保留一次)
  • 按Python默认sort()规则(首字母大写单词优先)排序后输出

现有代码问题

你当前的代码存在几个关键逻辑错误:

  1. 直接将整行文本加入列表,而非拆分后的单个单词
  2. 仅对列表第一行内容执行了split(),未遍历处理所有行的单词
  3. 没有实现去重逻辑,无法得到无重复的单词集合

现有代码:

list=[]
fname = input("Enter file name: ")
try:
    fh=open(fname)
except:
    print('File cannot be opened:',fname)
    quit()
fhand=open(fname)

for line in fhand:
    value=line.rstrip()
    list.append(value)
    list.sort()

    index=list[0].split()

print(index)

修正后的代码

# 用集合存储无重复单词(集合自动去重)
unique_words = set()
fname = input("Enter file name: ")

try:
    # 使用with语句自动管理文件资源,避免手动关闭的遗漏
    with open(fname, 'r') as fhand:
        for line in fhand:
            # 去除行尾换行符后拆分出所有单词
            words = line.rstrip().split()
            # 将整行单词批量加入集合
            unique_words.update(words)
except FileNotFoundError:
    print('File cannot be opened:', fname)
    quit()

# 将集合转为列表,按Python默认规则排序
sorted_words = sorted(unique_words)
print(sorted_words)

代码关键说明

  • 集合去重:集合的特性是元素唯一,无需手动判断单词是否已存在,比列表去重更高效
  • with语句:自动处理文件的打开与关闭,避免资源泄漏,是Python操作文件的推荐写法
  • 排序逻辑:sorted()函数默认采用Python的字母排序规则,大写字母开头的单词会排在小写单词前面,完全符合需求

运行后将输出你期望的结果:

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:31:04