python使用正则筛选信用卡

时间:2022-09-15 11:35:42

本文实例为大家分享了python使用正则筛选信用卡的具体代码,供大家参考,具体内容如下

本文来源于两个简单的题目:

1.判断一对单词是否是" anagrams "
2.判断信用卡是否合理

判断 anagramsstrong>

anagrams 的百度翻译:由颠倒字母顺序而构成的字(短语)

而题目给出例子:

[ dog , odg ]
[ dog , dog ]
[ dog , god ]
[ dog , gdo ]

均为 anagrams 。

那思路就简单了,直接拆分字母,排序,比较就 ok 。

判断信用卡

题目给出的要求如下:

the criteria are:
• it must start with a 4,5 or 6
• it must be exactly 16 digits
• it must be numbers only
• it can have a digits in groups of 4, separated by one hyphen “-“
• it should not contain any other characters.
• it must not have any 4 repeated digits.

样例输出如下:

378282246310005 invalid
30569309025904 invalid
6011111111111117 invalid
5123-2332-3232-3213 valid

py文件

两个题目合并在一个 py 文件中。 
而入参数分别是两个文件的名字,一个是 anagram.txt ,另一个是 credit_cards.txt ,他们分别长这样:

python使用正则筛选信用卡

python使用正则筛选信用卡

最后的程序长这样:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#! /usr/bin/python3
import re
###############################
##you need to implet the following methods:
##
##question 1
##anagram_validator()
##
##question 2
##credit_card_validator()
 
################################
 
###################################################
# question 1: check for anagrams:#
###################################################
 
def get_list(src_str):
 sub_list=[]
 word_tmp=''
 for word in src_str:
 if word != ',':
 word_tmp = word_tmp+word
 else:
 sub_list.append(word_tmp)
 word_tmp = ''
 return sub_list
 
def read_anagram(file_name):
 '''
 input: a file name
 return: a nested list of two words list
 example : [[word1,word2],[word3,word4]...etc]
 '''
 with open(file_name,encoding = 'utf-8') as f:
 return_list =[]
 file_conment = f.read()
 
 file_conment_new = re.sub(r'\n',',',file_conment)
 file_conment_new = file_conment_new+','
 subs_list = get_list(file_conment_new)
 i=0
 while i < (len(subs_list)-1):
 return_list.append([subs_list[i],subs_list[i+1]])
 i=i+2
 return return_list
 
 
 
def anagram_validator(anagram):
 '''
 input is the output from "read_anagram()".
 return: list of "anagrams" or "not anagrams" values for each two words
 example input (dog,gdo),(try,elm) then output would be ["anagrams","not anagrams"] with sequence of the input
 '''
 result_list=[]
 for i in range(len(anagram)):
 word_font = ''.join((lambda x:(x.sort(),x)[1])(list(anagram[i][0])))
 word_back = ''.join((lambda x:(x.sort(),x)[1])(list(anagram[i][1])))
 if word_font == word_back:
 result_list.append('anagrams')
 else:
 result_list.append('not anagrams')
 
 return result_list
 
############################################
# question 2: validate credit cards #
############################################
def read_credit_cards(file_name):
 '''
 input: a file name
 return tuple of numbers
 '''
 with open(file_name,encoding='utf-8') as f:
 card_conment = f.read()
 
 card_conment = re.sub(r'\[','',card_conment)
 card_conment = re.sub(r'\]','',card_conment)
 card_conment = card_conment+','
 card_list = get_list(card_conment)
 return tuple(card_list)
 
 
def credit_card_validator(numbers):
 '''
 input: tuple of numbers
 return:dictionary of credit card numbers where key is the number and value if valid or invalid
 '''
 validator_list=[]
 credit_dict={}
 for i in range(len(numbers)):
 validator_list.append(numbers[i])
 
 for i in range(len(numbers)):
 ch_num = 0
 repeat_flag = 0
 for ch in validator_list[i]:
 if ord("a")<=ord(ch)<=ord("z"):
 ch_num+=1
 break
 
 tmp_list = []
 tmp_list = (re.sub(r"[^\d]", "", validator_list[i]))
 for index in range(len(tmp_list)-4):
 if(tmp_list[index] == tmp_list[index+1] and
 tmp_list[index] == tmp_list[index+2] and
 tmp_list[index] == tmp_list[index+3] ):
 repeat_flag = 1
 break;
 
 if(validator_list[i][0] != '4' and
 validator_list[i][0] != '5' and
 validator_list[i][0] != '6' ):
 credit_dict[validator_list[i]]='invalid'
 elif( len(re.sub(r"\d", "", validator_list[i])) != 16 ):
 credit_dict[validator_list[i]]='invalid'
 elif(ch_num > 0):
 credit_dict[validator_list[i]]='invalid'
 elif(
 (re.search(r"-",validator_list[i])) and
  ( validator_list[i][4] != '-' or
  validator_list[i][9] != '-'or
  validator_list[i][14] != '-'
  )
 ):
 credit_dict[validator_list[i]]='invalid'
 elif(re.search(r"[^-\d]",validator_list[i])):
 credit_dict[validator_list[i]]='invalid'
 elif(repeat_flag == 1 ):
 credit_dict[validator_list[i]]='invalid'
 else :
 credit_dict[validator_list[i]]='valid'
 space_str = ''
 
 return credit_dict
 
 
def print_credit_card_summary(dict_o):
 '''
 input: dict
 return:
 printing summary of validation result - space between credit card and status is 40 width
 example:
 378282246310005 invalid
 30569309025904 invalid
 '''
 space_str = ''
 for key in dict_o:
 new_str = key + dict_o[key]
 if(dict_o[key] == "valid"):
 new_str_tmp = new_str[:-5]
 space_lenth = 46-len(new_str)
 for x in range(space_lenth):
 space_str +=' '
 print(new_str_tmp + space_str + 'valid')
 space_str=''
 else :
 new_str_tmp = new_str[:-7]
 space_lenth = 48-len(new_str)
 for x in range(space_lenth):
 space_str +=' '
 print(new_str_tmp + space_str + 'invalid')
 space_str=''
 
 
 
####### the code below is for testing###################
############### do not change #########################
 
 
import sys
 
if __name__ == '__main__':
 # take care of the console inputs
 if len(sys.argv) <= 1:
 sys.argv = ['', "anagram.txt", "credit_cards.txt"]
 stars = '*' * 40
 print(stars)
 print("testing question 1 --- anagrams?")
 print(stars)
 
 # testing reading_anagrams
 try:
 anagram = read_anagram(sys.argv[1])
 if not anagram:
 print("read_anagram() returns none.")
 else:
 print("anagram: ", anagram)
 print()
 except exception as e:
 print("error (readnumbers()): ", e)
 
 # testing anagram_validator
 anagrams = 0
 nanagrams = 0
 try:
 if not anagram: # question 1 has not been implemented
 print("anagram_validator() skipped....")
 else:
 result = anagram_validator(anagram)
 if result == none:
 print("anagram_validator() returns none.")
 else:
 for i in result:
  if i == "anagrams":
  anagrams += 1
  elif i == "not anagrams":
  nanagrams += 1
 print("number of valid anagrams is {} and not anagrams is {}.".format(anagrams, nanagrams))
 
 except exception as e:
 print("error (anagram_validator()):", e)
 
 # testing question 2
 
 print("\n\n" + stars)
 print("testing question 2 --- credit card validator")
 print(stars)
 
 # testing reading_credit_cards
 try:
 tup = read_credit_cards(sys.argv[2])
 if not tup:
 print("read_credit_cards() returns none.")
 else:
 print("the tuple of credit_cards: {}".format(tup))
 except exception as e:
 print("error (read_credit_cards()):", e)
 
 # testing credit_card_validator
 vcc = 0
 ivcc = 0
 try:
 if not tup: # readin_question 2 has not been implemented
 print("credit_card_validator() skipped...")
 else:
 cc_dict = credit_card_validator(tup)
 tmp_cc_dict = cc_dict
 if not cc_dict:
 print("credit_card_validator() returns none.")
 else:
 for items in cc_dict.keys():
  if cc_dict[items] == "valid":
  vcc += 1
  elif cc_dict[items] == "invalid":
  ivcc += 1
 print("number of valid credit cards is {} and invalid {}.".format(vcc, ivcc))
 except exception as e:
 print("error (credit_card_validator()):", e)
 
 # testing question 2
 print("\n\n" + stars)
 print("testing question 2b --- print credit card summary")
 print(stars)
 # testing print_credit_card_summary
 try:
 if not tmp_cc_dict: # dict credit card output has not been implemented
 print("print_credit_card_summary() skipped...")
 else:
 import io # do not delete this line
 from contextlib import redirect_stdout # do not delete this line
 
 f = io.stringio()
 with redirect_stdout(f):
 print_credit_card_summary(tmp_cc_dict)
 out = f.getvalue()
 if not out:
 print("print_credit_card_summary() returns none.")
 else:
 count44 = 0
 count46 = 0
 for line in out.splitlines():
  if len(line) - len(line.split()) == 44:
  count44 += 1
  elif len(line) - len(line.split()) == 46:
  count46 += 1
 if count44 == vcc and count46 == ivcc:
  print("your format looks good")
 else:
  print("you might have some issues in your summary format")
 
 
 except exception as e:
 print("error (print_credit_card_summary()):", e)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_30650153/article/details/84110948