[Python] 專題五.列表基礎知識 二維list排序、獲取下標和處理txt文字例項
阿新 • • 發佈:2019-02-06
通常測試人員或公司實習人員需要處理一些txt文字內容,而此時使用Python是比較方便的語言。它不光在爬取網上資料上方便,還在NLP自然語言處理方面擁有獨到的優勢。這篇文章主要簡單的介紹使用Python處理txt漢字文字、二維列表排序和獲取list下標。希望文章對你有所幫助或提供一些見解~
一. list二維陣列排序
功能:已經通過Python從維基百科中獲取了國家的國土面積和排名資訊,此時需要獲取國土面積並進行排序判斷世界排名是否正確。
列表基礎知識
列表型別同字串一樣也是序列式的資料型別,可以通過下標或切片操作來訪問某一個或某一塊連續的元素。它和字串不同之處在於:字串只能由字元組成而且不可變的(不能單獨改變它的某個值),而列表是能保留任意數目的Python物件靈活容器。
總之,列表可以包含不同型別的物件(包括使用者自定義的物件)作為元素,列表可以新增或刪除元素,也可以合併或拆分列表,包括insert、update、remove、sprt、reverse等操作。
列表排序介紹
常用列表排序方法包括使用List內建函式list.sort()或序列型別函式sorted(list)排序
#list.sort(func=None, key=None, reverse=False)
list = [4, 3, 9, 1, 5, 2]
print list
list.sort()
print list
#輸出
[4, 3, 9, 1, 5, 2]
[1, 2, 3, 4, 5, 9]
通過對比下面的程式碼,可以發現兩種方法的區別是:list.sort()改變了原list的順序,而sorted沒有。#sorted(list) list = ['h', 'a', 'p', 'd', 'i', 'b'] print list print sorted(list) print list #輸出 ['h', 'a', 'p', 'd', 'i', 'b'] ['a', 'b', 'd', 'h', 'i', 'p'] ['h', 'a', 'p', 'd', 'i', 'b']
二維列表排序
通過lambda表示式實現二維列表排序,並且按照第二個關鍵字進行排序。參考
題目中如果第一個數儲存檔案中讀取的行號,第二個數儲存人口數量,此時可對第二個數進行排序。需要注意的是它們一組(1,93)是tuple元組。#list.sort(func=None, key=None, reverse=False) list = [('Tom',4),('Jack',7),('Daly',9),('Mary',1),('God',5),('Yuri',3)] print list list.sort(lambda x,y:cmp(x[1],y[1])) print list #輸出 [('Tom', 4), ('Jack', 7), ('Daly', 9), ('Mary', 1), ('God', 5), ('Yuri', 3)] [('Mary', 1), ('Yuri', 3), ('Tom', 4), ('God', 5), ('Jack', 7), ('Daly', 9)]
#list.sort(func=None, key=None, reverse=False)
list = [(1,93),(2,71),(3,89),(4,93),(5,85),(6,77)]
print list
list.sort(key=lambda x:x[1])
print list
#輸出
[(1, 93), (2, 71), (3, 89), (4, 93), (5, 85), (6, 77)]
[(2, 71), (6, 77), (5, 85), (3, 89), (1, 93), (4, 93)]
lambada表示式
在上述程式碼中,如果還不知道lambada是什麼鬼東西的話?那我就來幫你回顧了。
python允許使用lambda關鍵字創造匿名函式,它不需要以標準的方式來宣告,如def語句。然而作為函式,它們也能有引數。
lambda就是一個表示式,而不是一個程式碼塊。而且這個表達是的定義必須和宣告放在同一行,能在lambda中封裝有限的邏輯進去,起到一個函式速寫的作用。例如:
#lambda [arg1[, arg2, ..., argN]]:expression
f = lambda x,y,z:x+y+z
num = f(1,2,3)
print 'lambda: ' + str(num)
#等價於
def add(x,y,z):
return x+y+z
num = add(1,2,3)
print 'function: ' + str(num)
#輸出
lambda: 6
function: 6
二. 處理txt文字
下面是通過txt檔案按行讀取,並獲取面積進行排序。其中核心程式碼如下:
讀取檔案&列表新增
source = open("F:\\Student\\1Area.txt",'r')
lines = source.readlines()
L = [] #列表二維 國家行數 人口數
count = 1 #當前國家在檔案中第count行
for line in lines:
line = line.rstrip('\n') #去除換行
.... #獲取排名和麵積
fNum = string.atof(number) #面積
L.append((count,ffNum)) #列表新增
count = count + 1
else:
print 'End While'
source.close()
列表排序
L.sort(lambda x,y:cmp(x[1],y[1]),reverse = True)
#遍歷過程 表示第i名 (檔案第x行,面積y平方公里)
#重點 L[i]輸出列表 1 (46, 17075200.0) L[i][0]表示元組tuple第一個數 1 46
for i in range(len(L)):
print (i+1), L[i]
獲取面積字串line = line.rstrip('\n') #去除換行
start = line.find(r'V:')
end = line.find(r'平方公里')
number = line[start+2:end]
number = number.replace(',','') #去除','
#輸出
line => C:國家 E:中華人民共和國 A:國土面積 V:9,634,057或9,736,000平方公里(世界第3/4名)
number => 9634057或9736000
最後同時需要處理各種字串情況,如‘或’、‘萬’要乘10000、刪除‘[1]’等。更簡單的方法是通過正則表示式或獲取第一個非數字字元。
執行結果如下所示,排序後的txt和糾錯txt:
程式碼如下:
# coding=utf-8
import time
import re
import os
import string
import sys
source = open("F:\\Student\\1Area.txt",'r')
lines = source.readlines()
count = 1
L = [] #列表二維 國家行數 人口數
'''
第一部分 獲取國土面積
'''
print 'Start!!!'
for line in lines:
line = line.rstrip('\n') #去除換行
start = line.find(r'V:')
end = line.find(r'平方公里')
number = line[start+2:end]
number = number.replace(',','') #去除','
fNum = 0.0
if '萬' in number:
end = line.find(r'萬')
newNum = line[start+2:end]
fNum = string.atof(newNum)*10000
else: #如何優化程式碼 全域性變數
if '/' in number:
end = line.find(r'/')
newNum = line[start+2:end]
newNum = newNum.replace(',','')
fNum = string.atof(newNum)
elif '(' in number:
end = line.find(r'(')
newNum = line[start+2:end]
newNum = newNum.replace(',','')
fNum = string.atof(newNum)
elif '[' in number:
end = line.find(r'[')
newNum = line[start+2:end]
newNum = newNum.replace(',','')
fNum = string.atof(newNum)
elif '或' in number:
end = line.find(r'或')
newNum = line[start+2:end]
newNum = newNum.replace(',','')
fNum = string.atof(newNum)
elif ' ' in number:
end = line.find(r' ')
newNum = line[start+2:end]
newNum = newNum.replace(',','')
fNum = string.atof(newNum)
else:
fNum = string.atof(number)
#print line
#print number
#print fNum
L.append((count,fNum))
count = count + 1
else:
print 'End While'
source.close()
'''
第二部分 從大到小排序
參看 http://blog.chinaunix.net/uid-20775448-id-4222915.html
'''
L.sort(lambda x,y:cmp(x[1],y[1]),reverse = True)
#print L
#遍歷過程 表示第i名 (檔案第x行,面積y平方公里)
#重點 L[i]輸出列表 1 (46, 17075200.0) L[i][0]表示元組tuple第一個數 1 46
for i in range(len(L)):
print (i+1), L[i]
'''
第三部分 讀寫檔案
'''
source = open("F:\\Student\\1Area.txt",'r')
lines = source.readlines()
result = open("F:\\Student\\1NewArea.txt",'w')
count = 1
for line in lines:
line = line.rstrip('\n')
#獲取列表L中排名位置pm
pm = 0
for i in range(len(L)):
if count==L[i][0]:
pm = i+1
break
#獲取檔案中名次
if '世界第' in line:
start = line.find(r'世界第')
end = line.find(r'名')
number = line[start+9:end]
if '/' in number: #防止中國第3/4名
end = line.find(r'/')
number = line[start+9:end]
if '包括海外' in number:
number = '41'
print number,pm,type(number),type(pm)
if string.atoi(number)==pm:
line = line + ' 【排名正確】 【世界第' + str(pm) + '名】'
result.write(line+'\n')
else:
line = line + ' 【排名錯誤】 【世界第' + str(pm) + '名】'
result.write(line+'\n')
else: #檔案中沒有排名
line = line + ' 【新加排名】 【世界第' + str(pm) + '名】'
result.write(line+'\n')
count = count + 1
else:
print 'End Sorted'
source.close()
result.close()
'''
第四部分 輸出一個排序好的檔案 便於觀察
'''
source = open("F:\\Student\\1Area.txt",'r')
lines = source.readlines()
result = open("F:\\Student\\1NewSortArea.txt",'w')
#i表示第i名 L[i][0]表示行數
pm = 0
for i in range(len(L)):
pm = L[i][0]
count = 1
for line in lines:
line = line.rstrip('\n')
if count==pm:
line = line + ' 【世界第' + str(i+1) + '名】'
result.write(line+'\n')
break
else:
count = count + 1
else:
print 'End Sorted Second'
source.close()
result.close()
最後希望文章對你有所幫助,文章主要通過講述一個實際操作,幫你鞏固學習liet列表的二維排序和字串txt處理。如果文中有錯誤或不足之處,還請海涵~