浩晨众云网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
小编给大家分享一下如何使用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)
以上是“如何使用Python实现对文件进行单词划分并去重排序”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!