I want to extract the numbers only from before the “am” and “pm”. If “pm” not avalilable means then only from before “am”.
JavaScript
x
26
26
1
para = ["who done this on 23 october to 26th october from 2 am to 10am"]
2
3
def time_ext(para):
4
vals = []
5
samp_str = ''
6
for i in t:
7
if i.isnumeric() == True:
8
samp_str = samp_str+i
9
else:
10
if samp_str == '':
11
pass
12
else:
13
vals.append(samp_str)
14
samp_str = ''
15
if len(vals) > 0:
16
vals = [int(i) for i in vals]
17
else:
18
pass
19
return vals
20
21
22
print(time_ext(para))
23
24
# my output is = [23, 2]
25
# Expecting output is = [2, 10]
26
Advertisement
Answer
JavaScript
1
24
24
1
para = ["who done this on 23 october to 26th october from 2 am to 10am"]
2
3
def time_ext(t):
4
vals = []
5
6
for line in t:
7
words = line.split()
8
9
for i in range(len(words)):
10
word = words[i]
11
found = False
12
13
if word.endswith("am") or word.endswith("pm"):
14
word = word[:-2]
15
found = True
16
elif ((i + 1) < len(words)) and (words[i + 1] in ("am", "pm")):
17
found = True
18
19
if found and word.isnumeric():
20
vals.append(word)
21
return vals
22
23
print(time_ext(para))
24