最近開始活躍下微信羣,出了些小題目,看看你們的解體思路,分享一個小題目git
從給定字符串中提取姓名,字符串內容以下,提取姓名 ["張敏15 zhangmin15 ()", "楊丹丹 yangdandan (99999)", "錢鳳 qianfeng (84567)", "柏寧寧 bainingning (99999), 滕玥3 tengyue3 ()"]微信
收錄的部分答案以下app
1 # -*- coding: utf-8 -*- 2 # @Author : monleylu 3 # @Time : 2018/8/1 9:36 AM 4 import re 5 6 s = ["張敏15 zhangmin15 ()", "楊丹丹 yangdandan (99999)", "錢鳳 qianfeng (84567)", "柏寧寧 bainingning (99999), 滕玥3 tengyue3 ()"] 7 8 9 def ccy(): 10 names = [] 11 for i in s: 12 # print(len(i.split(" "))) 13 num = int(len(i.split(" ")) / 3) 14 for j in range(num): 15 names.append(i.split(" ")[j * 3]) 16 print(names) 17 18 19 def zdm(): 20 names = [] 21 for i in s: 22 str = re.sub("[A-Za-z0-9\\%\[\]\,\(\)]", "", i) 23 # print(str) 24 names.append(str) 25 print(names) 26 27 28 def zm(): 29 re = [] 30 for list_name_duo in s: 31 for list_name_dan in list_name_duo.split(','): 32 list_name = list(list_name_dan) 33 for j in range(1, len(list_name)): 34 if (list_name[j] == ' ' or str(list_name[j]).isdigit()): 35 name = ''.join(list_name[:j]).strip(' ') 36 re.append(name) 37 break 38 print(re) 39 40 41 def zh(): 42 for i in s: 43 result = i.split(' ')[:1] 44 print(result) 45 print("\n") 46 47 48 def byr(): 49 name = [] 50 for i in s: 51 s1 = i.split(",") 52 for j in s1: 53 j = j.lstrip() 54 name.append(j[0:j.index(" ")]) 55 print(name) 56 57 58 def qf(): 59 Names = [] 60 for n in s: 61 if ',' in n: 62 t = n.split(',') 63 for name in t: 64 # print(name) 65 Names.append(name.split(" ")[0]) 66 else: 67 name = n.split(" ")[0] 68 Names.append(name) 69 print(Names) 70 71 72 def zlm(): 73 for v in s: 74 if ',' in v: 75 tmp = v.split(',') 76 for i in tmp: 77 print(i.split(" ")[0]) 78 else: 79 print(v.split(" ")[0]) 80 81 82 def ml(): 83 name = [] 84 for i in s: 85 for j in i.split(","): 86 name.append(j.split()[0]) 87 print(name) 88 89 90 if __name__ == "__main__": 91 # bug 92 qf() 93 94 # ok 95 byr() 96 97 # bug 98 zh() 99 100 # ok 101 zm() 102 103 # ok 104 zdm() 105 106 # ok 107 ccy() 108 109 # ok 110 zlm() 111 112 # ok 113 ml()