<Python>將一個有序排列的txt文件,打亂成無序排列,再輸出到指定文件中

功能:

現有一個文件“1.txt”,裏面的內容是:

00176480_nohash_0_bed
00176480_nohash_0_down
00176480_nohash_0_left
00176480_nohash_0_marvin
00176480_nohash_0_off
00176480_nohash_0_one
00176480_nohash_1_marvin
004ae714_nohash_0_bed
004ae714_nohash_0_cat
004ae714_nohash_0_down
004ae714_nohash_0_eight
004ae714_nohash_0_five
004ae714_nohash_0_four
004ae714_nohash_0_go
004ae714_nohash_0_left
004ae714_nohash_0_off

需要將裏面的排序進行打亂,再存儲到“2.txt”文件中

代碼寫的簡單,作爲一個C++程序員,正在努力學習python

代碼:

import random

def ReadFileDatas():
    FileNamelist = []
    file = open('1.txt','r+')
    for line in file:
        line=line.strip('\n') #刪除每一行的\n
        FileNamelist.append(line)
    print('len ( FileNamelist ) = ' ,len(FileNamelist))
    file.close()
    return FileNamelist

def WriteDatasToFile(listInfo):
    file_handle=open('2.txt',mode='a')
    for idx in range(len(listInfo)):
        str = listInfo[idx]
        #查找最後一個 “_”的位置
        ndex = str.rfind('_')
        #print('ndex = ',ndex)
        #截取字符串
        str_houZhui = str[(ndex+1):]
        #print('str_houZhui = ',str_houZhui)
        str_Result = str + ' ' + str_houZhui+'\n'
        print(str_Result)
        file_handle.write(str_Result)
    file_handle.close()

if __name__ == "__main__":
    listFileInfo = ReadFileDatas()
    #打亂列表中的順序
    random.shuffle(listFileInfo)
    WriteDatasToFile(listFileInfo)

“2.txt”文件的最後結果

102192fd_nohash_0_bed bed
c93d5e22_nohash_2_left left
72aa7259_nohash_0_right right
80c17118_nohash_0_seven seven
15c563d7_nohash_0_dog dog
611d2b50_nohash_3_no no
eb67fcbc_nohash_0_seven seven
b5935410_nohash_0_off off
6846af18_nohash_1_left left
01648c51_nohash_0_nine nine
ceaadb24_nohash_1_bird bird
6ceeb9aa_nohash_0_five five

9e42ae25_nohash_0_marvin marvin


在此,我要特意說明的函數:

random.shuffle(列表)

python很強大,一個函數就可以搞定這個功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章