Python实现文件单词提取、去重与排序
本文介绍使用Python读取文本文件,提取其中的单词并进行去重和排序的操作。通过两种不同的代码实现方式(二重循环与集合转换),展示了如何从文件中获取唯一单词列表并按字母顺序输出,供学习者参考。
本文通过具体示例,演示如何利用Python语言对文件内容进行单词分割、去重及排序处理。
测试文件名:test1.txt
文件包含的内容如下:
But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief
程序运行后的预期输出结果如下:
Enter file name: "test1.txt" ['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']
PR4E教程中采用append方法实现的代码(涉及二重循环逻辑):
import sys
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print(lst)
另一种使用单层循环结合集合去重的实现方式:
import string
fname = input("Enter file name: ")
fh = open(fname)
l = list()
for line in fh:
line = line.rstrip()
l = l + list(line.split())
s = list(set(l))
s.sort()
print(s)
此外,以下提供几款辅助工具供读者参考使用:
在线去除重复项工具: http://tools.jb51.net/code/quchong
在线文本去重工具: http://tools.jb51.net/aideddesign/txt_quchong
在线动画演示插入/选择/冒泡/归并/希尔/快速排序算法过程工具: http://tools.jb51.net/aideddesign/paixu_ys
如需了解更多Python相关知识,可查阅本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》。
希望上述内容能对您的Python编程学习有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









