不管是誰,只要處理過由用戶提交的調(diào)查數(shù)據(jù),就能明白這種亂七八糟的數(shù)據(jù)是怎么一回事。為了得到一組能用于分析工作的格式統(tǒng)一的字符串,需要做很多事情:去除空白符、刪除各種標(biāo)點(diǎn)符號(hào)、正確的大寫格式等。做法之一是使用內(nèi)建的字符串方法和正則表達(dá)式re模塊:
創(chuàng)新互聯(lián)專注于網(wǎng)站建設(shè)|網(wǎng)站維護(hù)|優(yōu)化|托管以及網(wǎng)絡(luò)推廣,積累了大量的網(wǎng)站設(shè)計(jì)與制作經(jīng)驗(yàn),為許多企業(yè)提供了網(wǎng)站定制設(shè)計(jì)服務(wù),案例作品覆蓋紗窗等行業(yè)。能根據(jù)企業(yè)所處的行業(yè)與銷售的產(chǎn)品,結(jié)合品牌形象的塑造,量身定制品質(zhì)網(wǎng)站。
states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda',
'south carolina##', 'West virginia?']
import re
def clean_strings(strings): # 一般對(duì)數(shù)據(jù)的處理步驟
result = []
for value in strings:
value = value.strip()
value = re.sub('[!#?]', '', value)
value = value.title()
result.append(value)
return result
In [173]: clean_strings(states)
Out[173]:
['Alabama',
'Georgia',
'Georgia',
'Georgia',
'Florida',
'South Carolina',
'West Virginia']
def remove_punctuation(value):
return re.sub('[!#?]', '', value)
clean_ops = [str.strip, remove_punctuation, str.title] # 函數(shù)也是對(duì)象
def clean_strings(strings, ops):
result = []
for value in strings:
for function in ops:
value = function(value)
result.append(value)
return result
In [175]: clean_strings(states, clean_ops)
Out[175]:
['Alabama',
'Georgia',
'Georgia',
'Georgia',
'Florida',
'South Carolina',
'West Virginia']
# 或者
In [176]: for x in map(remove_punctuation, states): #
.....: print(x)
Alabama
Georgia
Georgia
georgia
FlOrIda
south carolina
West virginia