ccf 201803-3 URL映射(python)

 使用正則表達式git

 1 import re
 2 import collections
 3 n, m = list(map(int, input().split()))
 4 arr = ['']*(m+n)
 5 for i in range(n+m):
 6     arr[i] = input()
 7 
 8 def get_rule(rule):
 9     result = ""
10     for test in re.findall(r"(/[^/]*)", rule):
11         if re.match(r"/<int>", test):
12             result += "/(\d+)"
13         elif re.match(r"/<str>", test):
14             result += "/(\w+)"
15         elif re.match(r"/<path>", test):
16             result += "/([\w/.]*)"
17         else:
18             result += test
19     return result + "$"
20 
21 # 首先現將規則作成collection
22 rule_map = collections.OrderedDict()
23 for test in arr[0:n]:
24     rule_map[test.split(' ')[1]] = get_rule(test.split(' ')[0])
25 
26 # 將規則作成字典,每遇到一個路徑,就跟全部規則比對
27 for test in arr[n:n+m]:  # 遍歷全部規則
28     for name, rule in rule_map.items():
29         if re.match(rule, test):
30             print(name,end = " ")
31             # 注意若是是數字,須要去掉前導0,例09—>9
32             for i in re.match(rule, test).groups():
33                 print(int(i) if i.isdigit() else i,end = " ")
34             print() # 換行
35             break
36     else:
37         print("404")

相關文章
相關標籤/搜索