编程小白第一本入门书(二)
作者:互联网
1.检查手机号
1 def sendTextNumber(): 2 3 CN_mobile = ['134','135','136','137','138','139', 4 '150','151','152','157','158','159', 5 '182','183','184','187','188','147','178','1705'] 6 CN_union = ['130','131','132','155','156','185','186','145','176','1709'] 7 CN_telecom = ['133','153','180','181','189','177','1700'] 8 9 phone_num = input('Enter your number:') 10 11 if len(phone_num) != 11: 12 print('Invalid length,your number should be in 11 digits') 13 sendTextNumber() 14 elif phone_num[:3] in CN_mobile or phone_num[:4] == '1705': 15 print("Operator:China mobile") 16 print("We'are sending verification coed via text to your phone:",phone_num) 17 elif phone_num[:3] in CN_union or phone_num[:4] == '1709': 18 print("Operator:China union") 19 print("We'are sending verification coed via text to your phone:",phone_num) 20 elif phone_num[:3] in CN_telecom or phone_num[:4] == '1700': 21 print("Operator:China telecom") 22 print("We'are sending verification coed via text to your phone:",phone_num) 23 else: 24 print("No such a operator") 25 sendTextNumber()
1 sendTextNumber()
python3里面input默认接收到的是str类型:
1 a = input("input number:") 2 type(a)
>>>input number:12345 >>>Out[8]:str
1 def sendTextNumber(): 2 3 CN_mobile = [134,135,136,137,138,139, 4 150,151,152,157,158,159, 5 182,183,184,187,188,147,178,1705] 6 CN_union = [130,131,132,155,156,185,186,145,176,1709] 7 CN_telecom = [133,153,180,181,189,177,1700] 8 9 phone_num = input('Enter your number:') 10 num1 = int(phone_num[:3]) #转int 11 num2 = int(phone_num[:4]) #转int 12 if len(phone_num) != 11: 13 print('Invalid length,your number should be in 11 digits') 14 sendTextNumber() 15 elif num1 in CN_mobile or num2 == 1705: 16 print("Operator:China mobile") 17 print("We'are sending verification coed via text to your phone:{}".format(phone_num)) 18 elif num1 in CN_union or num2 == 1709: 19 print("Operator:China union") 20 print("We'are sending verification coed via text to your phone:{}".format(phone_num)) 21 elif num1 in CN_telecom or num2 == 1700: 22 print("Operator:China telecom") 23 print("We'are sending verification coed via text to your phone:{}".format(phone_num)) 24 else: 25 print("No such a operator") 26 sendTextNumber() 27 sendTextNumber()
2.extend():向列表添加多个元素
1 aList = [123,'xyz','zara','abc'] 2 bList = ['manni',2009] 3 aList.extend(bList) 4 print(aList)
>>>[123, 'xyz', 'zara', 'abc', 'manni', 2009]
3.update():向字典添加多个元素
1 dict1 = {'name':'Mary','Age':27} 2 dict2 = {'sex':'female'} 3 dict1.update(dict2) 4 print(dict1)
>>>{'name': 'Mary', 'Age': 27, 'sex': 'female'}
4.zip()
1 a = [1,2,3] 2 b =[4,5,6] 3 c = [4,5,6,7,8] 4 zipped = zip(a,b) #将可迭代对象中对应的元素打包成一个个元组 5 zipped #返回由这些元组组成的对象
>>><zip at 0x1abbd618848>
6 list(zipped) #转化为列表
>>>[(1, 4), (2, 5), (3, 6)]
7 list(zip(a,c)) #元素的个数与最短的列表一致
>>>[(1, 4), (2, 5), (3, 6)]
8 a1,a2 = zip(*zip(a,b)) #zip(*)与zip相反,理解为解压 9 a1
>>>(1, 2, 3)
10 list(a2)
>>>[4, 5, 6]
5.解析式
使用解析式的效率更高。虚线前理解为想要放在列表中的元素。
1 a = [i**2 for i in range(1,10)] 2 b = [n for n in range(1,10) if n%2 == 0] 3 c = [letter.lower() for letter in 'ABCDEFGHI']
字典推导式:
1 d = {i:i+1 for i in range(4)} 2 f = {i:j.upper() for i,j in zip(range(1,6),'abcde')}
6.enumerate():给出数据和下标,一般用在for循环之中
1 seasons = ['Spring','Summer','Fall','Winter'] 2 enumerate(seasons)
>>><enumerate at 0x1abbd62fd38>
3 list(enumerate(seasons))
>>>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
4 list(enumerate(seasons,start=1))
>>>[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
for循环使用:
1 seq = ['one','two','three'] 2 for i,element in enumerate(seq): 3 print(i,element)
>>>0 one >>>1 two >>>2 three
1 letters = list('abcdefg') 2 for num,letter in enumerate(letters): 3 print(letter,'is',num+1)
a is 1 b is 2 c is 3 d is 4 e is 5 f is 6 g is 7
7.split()方法:指定分隔符对字符串进行切片
1 str = "Line1-abcedf \nLine2-abc \nLine4-abcd" 2 print(str.split()) #默认以空格为分隔符,包含 \n,返回分割后的字符串列表 3 print(str.split(' ',1)) #以空格为分隔符,分割1次,分割成2个
['Line1-abcedf', 'Line2-abc', 'Line4-abcd'] ['Line1-abcedf', '\nLine2-abc \nLine4-abcd']
1 txt = "Google#Runoob#Taobao#Facebook" 2 print(txt.split("#",1)) 3 print(txt.split("#"))
['Google', 'Runoob#Taobao#Facebook'] ['Google', 'Runoob', 'Taobao', 'Facebook']
8.count()方法:统计字符串里某个字符出现的次数。
1 str = "this is string example...wow!!!" 2 sub1 = "i" 3 print(str.count(sub1)) 4 sub2 = "wow" 5 print(str.count(sub2))
3 1
9.词频统计
1 path = "C:/Users/LKX/Desktop/Alice.txt" 2 with open(path,'r') as text: 3 words = text.read().split() 4 for word in words: 5 print("{}-{} times".format(word,words.count(word)))
部分输出:
ALICE'S-1 times ADVENTURES-1 times IN-1 times WONDERLAND-1 times Lewis-1 times Carroll-1 times THE-1 times MILLENNIUM-1 times FULCRUM-1 times EDITION-1 times 3.0-1 times CHAPTER-1 times I-19 times Down-1 times the-65 times Rabbit-Hole-1 times Alice-17 times was-42 times beginning-1 times to-50 times get-6 times very-18 times tired-1 times of-33 times sitting-1 times by-6 times her-17 times sister-2 times on-9 times the-65 times bank,-1 times and-42 times of-33 times
问题:带有标点符号的单词、重复展示、大小写不区分。
1 import string 2 3 path = "C:/Users/LKX/Desktop/Alice.txt" 4 5 with open(path,'r') as text: 6 words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]#去标点,转小写 7 words_index = set(words) #去重 8 counts_dict = {index:words.count(index) for index in words_index} #创建字典,键为单词,值为次数 9 10 for word in sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True): #按值(出现的次数)降序排列 11 print("{}-{} times".format(word,counts_dict[word]))
the-68 times to-52 times she-52 times and-48 times it-48 times was-43 times a-40 times of-33 times i-23 times down-22 times in-21 times alice-20 times her-19 times very-18 times that-18 times had-17 times but-16 times you-16 times not-14 times as-13 times for-12 times or-12 times think-11 times with-10 times on-10 times there-10 times all-10 times no-9 times little-9 times do-9 times up-9 times how-9 times so-9 times this-9 times at-9 times out-8 times me-8 times see-8 times time-8 times be-8 times if-7 times were-7 times would-7 times what-7 times about-7 times well-6 times rabbit-6 times one-6 times when-6 times like-6 times thought-6 times went-6 times get-6 times by-6 times say-6 times never-5 times nothing-5 times herself-5 times way-5 times much-5 times shall-5 times suddenly-5 times eat-5 times could-5 times either-5 times before-5 times wonder-5 times things-4 times moment-4 times bottle-4 times which-4 times my-4 times into-4 times is-4 times here-4 times off-4 times key-4 times oh-4 times looked-4 times found-4 times again-4 times fall-4 times upon-4 times they-4 times too-4 times cats-4 times then-4 times door-4 times dinah-4 times bats-4 times hall-4 times large-3 times first-3 times long-3 times through-3 times did-3 times any-3 times marked-3 times poison-3 times getting-3 times tried-3 times right-3 times ever-3 times began-3 times might-3 times said-3 times know-3 times round-3 times another-3 times even-3 times over-3 times sort-3 times after-3 times came-3 times rabbit-hole-3 times pictures-3 times passage-3 times fell-3 times look-3 times dear-3 times just-3 times book-3 times dark-3 times them-3 times drink-3 times use-3 times from-3 times nice-3 times golden-2 times bat-2 times behind-2 times small-2 times head-2 times mind-2 times an-2 times ran-2 times going-2 times ask-2 times though-2 times saw-2 times corner-2 times great-2 times whether-2 times rules-2 times deep-2 times people-2 times that's-2 times put-2 times those-2 times good-2 times once-2 times without-2 times it'll-2 times feet-2 times their-2 times jar-2 times took-2 times seemed-2 times hear-2 times several-2 times such-2 times latitude-2 times watch-2 times table-2 times sleepy-2 times air-2 times they'll-2 times close-2 times late-2 times white-2 times alice's-2 times saying-2 times rather-2 times thump-2 times made-2 times many-2 times across-2 times other-2 times waistcoat-pocket-2 times soon-2 times remember-2 times come-2 times have-2 times seen-2 times wish-2 times longitude-2 times considering-2 times begun-2 times miles-2 times rate-2 times anything-2 times low-2 times i've-2 times sister-2 times didn't-2 times however-2 times cupboards-2 times still-2 times falling-2 times turned-2 times among-2 times hot-2 times hand-2 times noticed-2 times doors-2 times somewhere-2 times it's-2 times got-2 times words-2 times earth-2 times quite-1 times knelt-1 times poor-1 times toffee-1 times every-1 times away-1 times wise-1 times wondered-1 times fortunately-1 times house-1 times afterwards-1 times along-1 times stairs-1 times cool-1 times dreamy-1 times answer-1 times presently-1 times glad-1 times printed-1 times ventured-1 times next-1 times taught-1 times conversation-1 times ought-1 times pink-1 times tired-1 times because-1 times felt-1 times natural-1 times lost-1 times read-1 times should-1 times only-1 times spoke--fancy-1 times twice-1 times stopping-1 times loveliest-1 times flowers-1 times book-shelves-1 times tea-time-1 times waiting-1 times locks-1 times burning-1 times curtsey-1 times inches-1 times go-1 times sometimes-1 times carroll-1 times fact-1 times knife-1 times four-1 times whiskers-1 times walked-1 times lewis-1 times sound-1 times filled-1 times top-1 times wouldn't-1 times trying-1 times few-1 times true-1 times saucer-1 times tumbling-1 times pegs-1 times feel-1 times side-1 times children-1 times afraid-1 times antipathies-1 times zealand-1 times word-1 times hold-1 times sadly-1 times trouble-1 times finding-1 times dipped-1 times cherry-tart-1 times field-1 times manage-1 times edition-1 times led-1 times earnestly-1 times miss-1 times sides-1 times later-1 times really-1 times matter-1 times fear-1 times your-1 times new-1 times high-1 times histories-1 times will-1 times funny-1 times been-1 times to-night-1 times curtain-1 times daisies-1 times almost-1 times home-1 times fulcrum-1 times certainly-1 times rat-hole-1 times mice-1 times make-1 times row-1 times ears-1 times bright-1 times longer-1 times begin-1 times name-1 times three-legged-1 times brave-1 times fountains-1 times orange-1 times find-1 times under-1 times label-1 times picking-1 times alas-1 times listening-1 times hurt-1 times leaves-1 times some-1 times dry-1 times friends-1 times walk-1 times hurrying-1 times end-1 times telescope-1 times dinah'll-1 times knowledge-1 times likely-1 times middle-1 times fifteen-1 times managed-1 times couldn't-1 times australia-1 times perhaps-1 times killing-1 times else-1 times day-1 times wander-1 times talking-1 times finished-1 times than-1 times its-1 times maps-1 times pine-apple-1 times curiosity-1 times 3.0-1 times i'll-1 times finger-1 times cat-1 times bleeds-1 times tunnel-1 times must-1 times let-1 times peeped-1 times having-1 times tell-1 times chapter-1 times plenty-1 times tiny-1 times dream-1 times shelves-1 times curtseying-1 times asking-1 times girl-1 times dozing-1 times schoolroom-1 times walking-1 times happened-1 times showing-1 times centre-1 times sitting-1 times letters-1 times hung-1 times lately-1 times written-1 times simple-1 times certain-1 times indeed-1 times lessons-1 times marmalade-1 times own-1 times itself-1 times ma'am-1 times overhead-1 times shut-1 times bank-1 times garden-1 times belong-1 times are-1 times lit-1 times taste-1 times worth-1 times distance--but-1 times longed-1 times except-1 times half-1 times stupid-1 times fitted-1 times paper-1 times now-1 times impossible-1 times back-1 times world-1 times daisy-chain-1 times lock-1 times reading-1 times happen-1 times hoping-1 times beds-1 times shoulders-1 times flashed-1 times country-1 times toast-1 times pleasure-1 times empty-1 times wondering-1 times turkey-1 times drop-1 times out-of-the-way-1 times glass-1 times truth-1 times catch-1 times ignorant-1 times usually-1 times started-1 times telescopes-1 times i'm-1 times remarkable-1 times aloud-1 times opened-1 times adventures-1 times deeply-1 times why-1 times somebody-1 times flavour-1 times custard-1 times shutting-1 times sticks-1 times beginning-1 times fallen-1 times disappointment-1 times mouse-1 times hanging-1 times seem-1 times hope-1 times sight-1 times actually-1 times cut-1 times roast-1 times eaten-1 times nor-1 times you're-1 times grand-1 times near-1 times downward-1 times who-1 times burn-1 times please-1 times poker-1 times red-hot-1 times heap-1 times question-1 times conversations-1 times beautifully-1 times solid-1 times opportunity-1 times buttered-1 times passed-1 times jumped-1 times thousand-1 times idea-1 times heads-1 times disagree-1 times hedge-1 times delight-1 times burnt-1 times beasts-1 times milk-1 times she'll-1 times straight-1 times yes-1 times pop-1 times wind-1 times eyes-1 times slowly-1 times doorway-1 times larger-1 times labelled-1 times locked-1 times practice-1 times hurried-1 times learnt-1 times wild-1 times listen-1 times roof-1 times mixed-1 times unpleasant-1 times sooner-1 times occurred-1 times take-1 times open-1 times making-1 times bit-1 times millennium-1 times lamps-1 times forgotten-1 times hurry-1 times past-1 times second-1 times neck-1 times coming-1 times wonderland-1 timesView Code
1.string.punctuation:所有的标点符号。
1 import string 2 print(string.punctuation)
output:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
2.strip()方法:用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
1 str = "123abcrunboo321" 2 print(str.strip("12"))
3abcrunboo3
1 str = "123abcrunboo3221" 2 print(str.strip("23b1"))
abcrunboo
1 str = "000003210runboo01230000" 2 print(str.strip("0"))
3210runboo0123
3.set():创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
1 test = ['one','two','three','one','four'] 2 set(test)
{'four', 'one', 'three', 'two'}
3 for index in set(test): 4 print(index)
three four one two
4.函数sorted():对所有可迭代的对象进行排序操作。返回重新排列的列表。
1 counts_dict = {'the':25,'alice':35,'run':19} 2 result = sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True) #值降序排列 3 print(result)
['alice', 'the', 'run']
标签:第一本,入门,编程,times,phone,num,str,print,CN 来源: https://www.cnblogs.com/direwolf22/p/12658619.html