通常測試人員或公司實習人員需要處理一些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表達式實現二維列表排序,并且按照第二個關鍵字進行排序。[參考](http://blog.chinaunix.net/uid-20775448-id-4222915.html)
~~~
#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)]
~~~
題目中如果第一個數存儲文件中讀取的行號,第二個數存儲人口數量,此時可對第二個數進行排序。需要注意的是它們一組(1,93)是tuple元組。
~~~
#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處理。如果文中有錯誤或不足之處,還請海涵~
(By:Eastmount 2015-9-16 晚上9點 [http://blog.csdn.net/eastmount/](http://blog.csdn.net/eastmount/))
- 前言
- [Python學習] 專題一.函數的基礎知識
- [Python學習] 專題二.條件語句和循環語句的基礎知識
- [Python學習] 專題三.字符串的基礎知識
- [Python學習] 簡單網絡爬蟲抓取博客文章及思想介紹
- [Python學習] 專題四.文件基礎知識
- [python學習] 簡單爬取維基百科程序語言消息盒
- [python學習] 簡單爬取圖片網站圖庫中圖片
- [python知識] 爬蟲知識之BeautifulSoup庫安裝及簡單介紹
- [python+nltk] 自然語言處理簡單介紹和NLTK壞境配置及入門知識(一)
- [python學習] 模仿瀏覽器下載CSDN源文并實現PDF格式備份
- [Python學習] 簡單爬取CSDN下載資源信息
- [Python] 專題五.列表基礎知識 二維list排序、獲取下標和處理txt文本實例
- [Python學習] 專題六.局部變量、全局變量global、導入模塊變量
- [python] 專題七.網絡編程之套接字Socket、TCP和UDP通信實例
- [python] 專題八.多線程編程之thread和threading