Python實現(xiàn)對文件進行單詞劃分并去重排序操作示例
本文實例講述了Python實現(xiàn)對文件進行單詞劃分并去重排序操作。分享給大家供大家參考,具體如下:
文件名:test1.txt
文件內(nèi)容:
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的寫法:(二重循環(huán))
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)
自己一重循環(huán)寫法:
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相關內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Phantomjs抓取渲染JS后的網(wǎng)頁(Python代碼)
phantomjs:我的理解就是它是一個無顯示的瀏覽器,也就是說除了不能顯示頁面內(nèi)容以外,瀏覽器能干的活兒它基本上都能干。下面我們就來利用他做點有趣的事情2016-05-05基于matplotlib中ion()和ioff()的使用詳解
這篇文章主要介紹了基于matplotlib中ion()和ioff()的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06python控制windows剪貼板,向剪貼板中寫入圖片的實例
今天小編就為大家分享一篇python控制windows剪貼板,向剪貼板中寫入圖片的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05windows環(huán)境中利用celery實現(xiàn)簡單任務隊列過程解析
這篇文章主要介紹了windows環(huán)境中利用celery實現(xiàn)簡單任務隊列過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11