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)
PS:這里再為大家提供幾款相關工具供大家參考使用:
希望本文所述對大家Python程序設計有所幫助。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python编程单词排序_Python实现对文件进行单词划分并去重排序操作示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python画圆并填充图形颜色_如何使用
- 下一篇: pythonweb开发面试_Python