Python实现对文件进行单词划分并去重排序操作示例

yipeiwu_com5年前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)

PS:这里再为大家提供几款相关工具供大家参考使用:

在线去除重复项工具:
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程序设计有所帮助。

相关文章

使用 Supervisor 监控 Python3 进程方式

使用 Supervisor 监控 Python3 进程方式

首先说明,Supervisor 只能安装在 Python 2.x 环境中! 但是基本上所有的 Linux 都同时预装了 Python 2.x 和 Python 3.x 版本,并且调用 p...

Django自定义分页效果

Django自定义分页效果

分页功能在每个网站都是必要的,对于分页来说,其实就是根据用户的输入计算出应该显示在页面上的数据在数据库表中的起始位置。 确定分页需求: 1. 每页显示的数据条数 2. 每页显示页号链接数...

python中通过selenium简单操作及元素定位知识点总结

python中通过selenium简单操作及元素定位知识点总结

  浏览器的简单操作 # 导入webdriver模块 # 创建driver对象,指定Chrome浏览器 driver = webdriver.Chrome() # 窗口...

pybind11在Windows下的使用教程

pybind11在Windows下的使用教程

Pybind11算是目前最方便的Python调用C++的工具了, 介绍一下在vs2019上写Python的扩展的HelloWorld 1. 去下载pybind11  ...

详解python statistics模块及函数用法

本节介绍 Python 中的另一个常用模块 —— statistics模块,该模块提供了用于计算数字数据的数理统计量的函数。它包含了很多函数,具体如下表:...