-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchinses_date_translator.py
1665 lines (1434 loc) · 63 KB
/
chinses_date_translator.py
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
import traceback
from typing import List, Tuple, Optional
import arrow
import regex as re
from loguru import logger
OP = {'>=', '<=', '='}
SMALL_MONTH = ['04', '06', '09', '11']
def str2int(s: str) -> int:
"""将字符串数字转为整数
:param s: 字符串数字
:return: 对应的整形数,如果不是数字返回0
"""
try:
res = int(s)
except Exception:
res = 0
return res
def word2number(s: str) -> int:
"""方法number_translator的辅助方法,可将[零-九]正确翻译为[0-9]
:param s: 大写数字
:return: 对应的整形数,如果不是数字返回-1
"""
return {
"零": 0,
"0": 0,
"一": 1,
"1": 1,
"二": 2,
"两": 2,
"2": 2,
"三": 3,
"3": 3,
"四": 4,
"4": 4,
"五": 5,
"5": 5,
"六": 6,
"6": 6,
"七": 7,
"7": 7,
"八": 8,
"8": 8,
"九": 9,
"9": 9,
}.get(s, -1)
def number_translator(target: str) -> str:
"""
该方法可以将字符串中所有的用汉字表示的数字转化为用阿拉伯数字表示的数字
如"这里有一千两百个人,六百零五个来自中国"可以转化为
"这里有1200个人,605个来自中国"
此外添加支持了部分不规则表达方法
如两万零六百五可转化为20650
两百一十四和两百十四都可以转化为214
一六零加一五八可以转化为160+158
该方法目前支持的正确转化范围是: 0 ~ 10^16 - 1
该功能模块具有良好的复用性
:param target: 待转化的字符串
:return: 转化完毕后的字符串
"""
# logger.debug(f"before number_translator: {target}")
# 省略叫法: 六亿五
pattern = re.compile(r"[一二两三四五六七八九123456789]亿[一二两三四五六七八九123456789](?!(万|千|百|十))")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("亿")
s = list(filter(None, s))
num = 0
if len(s) == 2:
num += word2number(s[0]) * 10 ** 8 + word2number(s[1]) * 10 ** 7
target = pattern.sub(str(num), target, 1)
# 省略叫法: 六万五
pattern = re.compile(r"[一二两三四五六七八九123456789]万[一二两三四五六七八九123456789](?!(千|百|十))")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("万")
s = list(filter(None, s))
num = 0
if len(s) == 2:
num += word2number(s[0]) * 10000 + word2number(s[1]) * 1000
target = pattern.sub(str(num), target, 1)
# 省略叫法: 六千五
pattern = re.compile(r"[一二两三四五六七八九123456789]千[一二两三四五六七八九123456789](?!(百|十))")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("千")
s = list(filter(None, s))
num = 0
if len(s) == 2:
num += word2number(s[0]) * 1000 + word2number(s[1]) * 100
target = pattern.sub(str(num), target, 1)
# 省略叫法: 六百五
pattern = re.compile(r"[一二两三四五六七八九123456789]百[一二两三四五六七八九123456789](?!十)")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("百")
s = list(filter(None, s))
num = 0
if len(s) == 2:
num += word2number(s[0]) * 100 + word2number(s[1]) * 10
target = pattern.sub(str(num), target, 1)
# 将单位前的文字先转为数字
pattern = re.compile(r"[零一二两三四五六七八九]")
match = pattern.finditer(target)
for m in match:
target = pattern.sub(str(word2number(m.group())), target, 1)
# 星期天表达式替换为星期7
pattern = re.compile("(?<=(周|星期))[末天日]")
match = pattern.finditer(target)
for m in match:
target = pattern.sub("7", target, 1)
# 转化单位`十`
pattern = re.compile("(?<!(周|星期))0?[0-9]?十[0-9]?")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("十")
num = 0
ten = str2int(s[0])
if ten == 0:
ten = 1
unit = str2int(s[1])
num = ten * 10 + unit
target = pattern.sub(str(num), target, 1)
# 转化单位`百`
pattern = re.compile("0?[1-9]百[0-9]?[0-9]?")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("百")
s = list(filter(None, s))
num = 0
if len(s) == 1:
hundred = int(s[0])
num += hundred * 100
elif len(s) == 2:
hundred = int(s[0])
num += hundred * 100
num += int(s[1])
target = pattern.sub(str(num), target, 1)
# 转化单位`千`
pattern = re.compile("0?[1-9]千[0-9]?[0-9]?[0-9]?")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("千")
s = list(filter(None, s))
num = 0
if len(s) == 1:
thousand = int(s[0])
num += thousand * 1000
elif len(s) == 2:
thousand = int(s[0])
num += thousand * 1000
num += int(s[1])
target = pattern.sub(str(num), target, 1)
# 转化单位`万`
pattern = re.compile("[0-9]+万[0-9]?[0-9]?[0-9]?[0-9]?")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("万")
s = list(filter(None, s))
num = 0
if len(s) == 1:
tenthousand = int(s[0])
num += tenthousand * 10000
elif len(s) == 2:
tenthousand = int(s[0])
num += tenthousand * 10000
num += int(s[1])
target = pattern.sub(str(num), target, 1)
# 转化单位`亿`
pattern = re.compile("[0-9]+亿[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?")
match = pattern.finditer(target)
for m in match:
group = m.group()
s = group.split("亿")
s = list(filter(None, s))
num = 0
if len(s) == 1:
yi = int(s[0])
num += yi * 10 ** 8
elif len(s) == 2:
yi = int(s[0])
num += yi * 10 ** 8
num += int(s[1])
target = pattern.sub(str(num), target, 1)
# logger.debug(f"after number_translator: {target}")
return target
def year_trans(text: str) -> List:
"""年份的转换, 返回一个时间段, 粒度为`天`
`最近3年`, 从当天往前推算3年
`前3年`, 计算本年之前三个完整年份
`n年前`, n = {1,2,3}, 返回往前推算n年的整个年份; n = {4}, 返回该年度上一年的最后一天
`n年后`, n = {1,2,3}, 返回大于往后推算n年的今; n = {4}, 返回大于该年度的1号
Args:
text (str): 输入文本
Returns:
List: 年份的开始和结束年月日
Examples:
>>> year_trans('去年下半年')
['2020-07-01', '2020-12-31']
>>> year_trans('最近半年')
['2021-01-05', '2021-07-05']
>>> year_trans('前三年')
['2018-01-01', '2020-12-31']
>>> year_trans('三年后')
['>=', '2024-07-09']
"""
def infer_year(text) -> int:
""" 一些特殊年份写法的推理
"""
year = -1
if '今年' in text or '现在' in text:
year = this_year
elif '去年' in text or '昨年' in text or '上一年' in text:
year = this_year - 1
elif '前年' in text:
year = this_year - 2
elif '明年' in text:
year = this_year + 1
elif '后年' in text:
year = this_year + 2
return year
def year_completion(str_year: str) -> str:
"""将省略的年份补充为完整的年份
2位年份小于40的认为是21世纪, 否则为是20世纪
3位年份小于100的认为是21世纪, 否则认为是10世纪~20世纪
Args:
input (str): 阿拉伯数字表示的年份, 允许2位数字到4位数字
Return:
return (str): 补全后的年份
Examples:
>>> '08'
'2008'
>>> '207'
'1207'
"""
year_len = len(str_year)
assert 2 <= year_len <= 4, f'数字年份长度不符合要求'
if year_len == 2:
num_year = int(str_year)
res = '20' + str_year if num_year <=40 else '19' + str_year
return res
if year_len == 3:
num_year = int(str_year)
res = '2' + str_year if num_year <=100 else '1' + str_year
return res
if year_len == 4:
return str_year
return -1
try:
# logger.debug(text)
this_year = arrow.now().year
## -------------------------------- 隐含时间段 --------------------------------- ##
# n年前
rule = r'([0-9半一二两三四五六七八九十]+年)(前)'
res = re.search(rule, text)
if res:
groups = res.groups()
print(groups)
# 半年前
if groups[0] == '半年':
month = arrow.now().shift(months=-6).format('YYYY-MM')
st = month + '-01'
ed = month + '-31'
return [st, ed]
pure_num = number_translator(groups[0][:-1]) if groups[0] else 0
# 3年前
if len(pure_num) <= 3:
year_ago = arrow.now().shift(years=-int(pure_num)).format('YYYY')
year_st = year_ago + '-01-01'
year_ed = year_ago + '-12-31'
return [year_st, year_ed]
# 2020年前
if len(pure_num) == 4:
return ['<=', str(int(pure_num)-1) + '-12-31']
# n年后
rule = r'([0-9半一二两三四五六七八九十]+年)(后)'
res = re.search(rule, text)
if res:
groups = res.groups()
print(groups)
# 半年后
if groups[0] == '半年':
return ['>=', arrow.now().shift(months=+6).format('YYYY-MM-DD')]
pure_num = number_translator(groups[0][:-1]) if groups[0] else 0
# 3年后
if len(pure_num) <= 3:
return ['>=', arrow.now().shift(years=+int(pure_num)).format('YYYY-MM-DD')]
# 2020年后
if len(pure_num) == 4:
return ['>=', str(pure_num) + '-01-01']
# `最近`等的表述, 此处是从现在往前推, 含`半年`
rule = r'(最近|近|过去)([0-9半一二两三四五六七八九十]+年)'
res = re.search(rule, text)
if res:
res = res.groups()
# print(res)
if len(res) == 2:
if res[1] == '半年':
recent_st = arrow.now().shift(months=-6).format('YYYY-MM-DD')
recent_ed = arrow.now().format('YYYY-MM-DD')
return [recent_st, recent_ed]
shift_year = int(number_translator(res[1][:-1]))
recent_st = arrow.now().shift(years=-shift_year).format('YYYY-MM-DD')
recent_ed = arrow.now().format('YYYY-MM-DD')
return [recent_st, recent_ed]
# `前3年`等的表述, 是去上一个年度的整年, 此处没有`半年`
rule = r'(前)([0-9一二两三四五六七八九十]+年)'
res = re.search(rule, text)
# print(res)
if res:
res = res.groups()
if len(res) == 2:
shift_year = int(number_translator(res[1])[:-1])
year_st = str(arrow.now().shift(years=-shift_year).year)
year_ed = str(arrow.now().shift(years=-1).year)
return [year_st + '-01-01', year_ed + '-12-31']
## --------------------------------- 指明年份 --------------------------------- ##
# 有数字的和特殊年份等, 此种情况可以带`上半年` , `下半年`等
rule = r"([0-9零一二两三四五六七八九十]{2,4})(年)"
res = re.search(rule, text)
# print(f'specific year: {res}')
if res:
res = res.groups()
if res:
str_year = number_translator(res[0])
year = year_completion(str_year)
# print(year)
if '上半年' in text or '前半年' in text:
year = str(year) if year != -1 else str(this_year)
year_st = year + '-01-01'
year_ed = year + '-06-30'
return [year_st, year_ed]
elif '下半年'in text or '后半年' in text:
year = str(year) if year != -1 else str(this_year)
year_st = year + '-07-01'
year_ed = year + '-12-31'
return [year_st, year_ed]
else:
year_st = year + '-01-01'
year_ed = year + '-12-31'
return [year_st, year_ed]
## --------------------------------- 特殊年份 --------------------------------- ##
# # 去年上半年, 下半年
rule = r"([前|去|昨|今|明|后]年)*([上|下|前|后])*(半年)"
res = re.search(rule, text)
if res:
res = res.groups()
# print(res)
if len(res) == 3 and res[0] is not None:
year = str(infer_year(res[0]))
if res[1] == '上' or res[1] == '前':
year_st = year + '-01-01'
year_ed = year + '-06-30'
return [year_st, year_ed]
elif res[1] == '下' or res[1] == '后':
year_st = year + '-07-01'
year_ed = year + '-12-31'
return [year_st, year_ed]
if len(res) == 3 and res[0] is None:
year = str(this_year)
# 半年: 默认为最近半年
if not res[1]: #
year_st = arrow.now().shift(months=-6).format('YYYY-MM-DD')
year_ed = arrow.now().format('YYYY-MM-DD')
return [year_st, year_ed]
# 上半年
if res[1] == '上' or res[1] == '前':
year_st = year + '-01-01'
year_ed = year + '-06-30'
return [year_st, year_ed]
# 下半年
elif res[1] == '下' or res[1] == '后':
year_st = year + '-07-01'
year_ed = year + '-12-31'
return [year_st, year_ed]
# 去年, 明年
rule = r"([前|去|昨|今|明|后]+)(年)"
res = re.search(rule, text)
if res:
year = str(infer_year(text))
return [year + '-01-01', year + '-12-31']
return []
except Exception:
traceback.print_exc()
return []
def season_trans(text: str, year_flag: bool = False) -> List:
"""季节的转换, 返回一个时间段
涉及到`近`和`最近`的不能直接按照当天推, 从上季度结束往前推
此函数中, `春夏秋冬` 和 `一二三四` 季度等价
Args:
text (str): 输入文本
year_flag (bool, optional): 季节前面是否有年份, 有的话在'前三个季度'这种处理会变为当
年的前三季度. Defaults to False.
Returns:
List: 季度的开始和结束年月日
Example:
>>> season_trans('前三个季度')
['2020-10-01', '2021-06-31']
>>> season_trans('去年前三个季度')
['2020-01-01', '2020-09-30']
>>> season_trans('春季')
['2021-01-01', '2021-03-31']
>>> season_trans('上个季度')
['2021-04-01', '2021-06-31']
"""
SEASON = {
'1': ['01-01', '03-31'],
'2': ['04-01', '06-30'],
'3': ['07-01', '09-30'],
'4': ['10-01', '12-31'],
}
def get_poem_season(text: str) -> List:
"""得到`春夏秋冬`的开始结束日期
为了和第n季度保持一致, 这里约定春季1~3月, 夏季为4~6月, 秋季为7~9, 冬季为10~12月
Args:
text (str): 带季节的文字
Returns:
List: 季节的开始结束日期
"""
this_year = arrow.now().format('YYYY')
season = ['1', '1']
if '春' in text:
season = SEASON.get('1')
elif '夏' in text:
season = SEASON.get('2')
elif '秋' in text:
season = SEASON.get('3')
elif '冬' in text:
season = SEASON.get('4')
season = [this_year + '-' + season[0], this_year + '-' + season[1]]
return season
def infer_month_by_season(season_num: int) -> List:
"""根据季节数往前推, 找到目标季节的开始结束日期
Args:
season_num (int): 往前推的季节数
Returns:
List: 季节的开始结束日期
"""
assert season_num >= 0, f'season_num < 0'
year_shift = 0
this_month = arrow.now().month
his_year = arrow.now().format('YYYY')
# 计算当前季度的开始月份
if this_month <= 3:
this_season_st = '01'
elif this_month <= 6:
this_season_st = '04'
elif this_month <= 9:
this_season_st = '07'
elif this_month <= 12:
this_season_st = '10'
# 计算本季度
if season_num == 0:
start = this_year + '-' + this_season_st + '-01'
month_end = int(this_season_st) + 2
month_end = '0' + str(month_end) if month_end < 10 else str(month_end)
end = this_year + '-' + month_end + '-31'
return [start, end]
# 计算当前月和当前季节开始月的差距, 如六月, 差距为 6 - 4 = 2个月
month_dist = this_month - int(this_season_st)
# 月份偏移量
month_shift = month_dist + season_num * 3
# 目标开始年月
year_st = arrow.now().shift(months=-month_shift).format('YYYY')
month_st = arrow.now().shift(months=-month_shift).format('MM')
# 目标结束年月
year_ed = arrow.now().shift(months=-(month_dist+1)).format('YYYY')
month_ed = arrow.now().shift(months=-(month_dist+1)).format('MM')
start = year_st + '-' + month_st + '-01'
end = year_ed + '-' + month_ed + '-31'
return [start, end]
try:
# logger.debug(text)
this_year = arrow.now().format('YYYY')
poem_season_rule = r'[春夏秋冬]+[季天]+'
common_num_season_rule = r'([0-9零一二两三四五六七八九十]+)(季|个季)'
# 春夏秋冬表明的季度
poem_season_word = re.search(poem_season_rule, text)
if poem_season_word:
season_st, season_ed = get_poem_season(poem_season_word.group())
return [season_st, season_ed]
# 特殊字符: 这个季度
this_season_rule = r'(本|这|这一|这1|当)+个*季'
this_season_res = re.search(this_season_rule, text)
if this_season_res:
res = infer_month_by_season(0)
return res
# 特殊字符: 上个季度
this_season_rule = r'(上|上个)+个*季'
this_season_res = re.search(this_season_rule, text)
if this_season_res:
res = infer_month_by_season(1)
return res
# 数字表明的季度
season_num = re.search(common_num_season_rule, text)
if season_num:
season_number = number_translator(season_num.group())[0]
this_month = arrow.now().month
if season_number:
# 特殊字符: 前n季度 前面带年
year_flag_season_rule = r'(偂)([1-4一二两三四])+(季|个季)'
year_flag_season_res = re.search(year_flag_season_rule, text)
if year_flag and year_flag_season_res:
groups = year_flag_season_res.groups()
text_season_number = groups[1]
pure_season_num = number_translator(text_season_number) # 只能是1,2,3,4
if pure_season_num in SEASON:
season_st = SEASON.get('1')[0]
season_ed = SEASON.get(pure_season_num)[1]
return [this_year + '-' + season_st, this_year + '-' + season_ed]
# 特殊字符: 前|最近...|n季度
#! 这里往前推可能会改变年份
recent_season_rule = r'(最近|近|前|上|过去)+([0-9零一二两三四五六七八九十]*)(季|个季)'
season_num_res = re.search(recent_season_rule, text)
if season_num_res:
season_num_group = season_num_res.groups()
if len(season_num_group) == 3:
pure_season_num = season_num_group[1]
# 中间没有数字的, 默认为1
if pure_season_num == '':
res = infer_month_by_season(1)
# 中间有数字的
else:
pure_season_num = number_translator(pure_season_num)
res = infer_month_by_season(int(pure_season_num))
return res
# 纯数字
season_st, season_ed = SEASON.get(season_number, [None, None])
if season_st and season_ed:
return [this_year + '-' + season_st, this_year + '-' + season_ed]
return []
except Exception:
traceback.print_exc()
return []
def month_trans(text: str, year_flag: bool = False) -> List:
"""月份的转换, 返回一个时间段
`最近3月`等词, 从当天往前推算3个月
`前三月`等词, 计算本月之前三个完整月份
`n月前`, n = {1, 2}, 返回本年度该月份前一个月的31号之前
`n月后`, n = {1, 2}, 返回本年度该月份前一个月的1号之后
`n个月前`, n = {1,2,3}, 返回当前时间往前推算n个月的整个月份
`n个月后`, n = {1,2,3}, 返回当前时间往后推算n个月的1号
Args:
text (str): 输入文本
year_flag (bool, optional): 月份前面是否有年份, 有的话在'前三个月'这种处理会变为当
年的前三个月. Defaults to False.
Returns:
List: 月份的开始和结束年月日
Example:
>>> month_trans('本月')
['2021-07-01', '2021-07-31']
>>> month_trans('最近三个月')
['2021-04-05', '2021-07-05']
>>> month_trans('前三个月')
['2021-04-01', '2021-06-31']
>>> month_trans('四个月前')
[('2021-03-01', '2021-03-31')]
"""
try:
# logger.debug(text)
this_year = arrow.now().format('YYYY')
this_month = arrow.now().format('MM')
this_month_rule = r'[本|这|当]+[1|一]*个*月'
recent_month_num_rule = r'(最近|近)([0-9一二两三四五六七八九十]+)(月|个月)'
before_month_num_rule = r'(过去|前|上)([0-9一二两三四五六七八九十]*)(月|个月)'
several_month_before_rule = r'([0-9一二两三四五六七八九十]+)(个月)(前)'
several_month_after_rule = r'([0-9一二两三四五六七八九十]+)(个月)(后)'
specific_month_before_rule = r'([0-9一二两三四五六七八九十]{1,2})(月|月份)(前)'
specific_month_after_rule = r'([0-9一二两三四五六七八九十]{1,2})(月|月份)(后)'
year_flag_month_rule = r'(偂)([0-9一二两三四五六七八九十]+)(月|个月)'
specific_month_num_rule = r'([0-9一二两三四五六七八九十]+)(月)'
# 这个月 本月 ...
this_month_res = re.search(this_month_rule, text)
if this_month_res:
month_st = this_year + '-' + this_month + '-01'
month_ed = this_year + '-' + this_month + '-31'
return [month_st, month_ed]
# 最近几个月 #!可能跨过年份 从今天往前推
recent_month_res = re.search(recent_month_num_rule, text)
if recent_month_res:
recent_month_group = recent_month_res.groups()
if len(recent_month_group) == 3:
pure_month_num = recent_month_group[1]
shift_month = int(number_translator(pure_month_num)) if pure_month_num else 1
month_st = arrow.now().shift(months=-shift_month).format('YYYY-MM-DD')
month_ed = arrow.now().format('YYYY-MM-DD')
return [month_st, month_ed]
# n个月前/后
several_month_before_res = re.search(several_month_before_rule, text)
if several_month_before_res:
groups = several_month_before_res.groups()
shift_month = int(number_translator(groups[0]))
month = arrow.now().shift(months=-shift_month).format('YYYY-MM')
month_st = month + '-01'
month_ed = month + '-31'
return [month_st, month_ed]
several_month_after_res = re.search(several_month_after_rule, text)
if several_month_after_res:
groups = several_month_after_res.groups()
shift_month = int(number_translator(groups[0]))
month_day = arrow.now().shift(months=+shift_month).format('YYYY-MM-DD')
return ['>=', month_day]
# n月前/后
specific_month_before_res = re.search(specific_month_before_rule, text)
if specific_month_before_res:
groups = specific_month_before_res.groups()
month = int(number_translator(groups[0]))
if month == 1:
return ['<=', str(int(this_year) - 1) + '-12-31']
if 2 <= month <= 10:
return ['<=', this_year + '-0' + str(month-1) + '-31']
if 11 <= month <=12:
return ['<=', this_year + '-' + str(month) + '-31']
specific_month_after_res = re.search(specific_month_after_rule, text)
if specific_month_after_res:
groups = specific_month_after_res.groups()
month = int(number_translator(groups[0]))
if 1 <= month <= 9:
return ['>=', this_year + '-0' + str(month) + '-01']
if 10 <= month <= 12:
return ['>=', this_year + '-' + str(month) + '-01']
# 前n个月 前面带年
year_flag_month_res = re.search(year_flag_month_rule, text)
if year_flag and year_flag_month_res:
groups = year_flag_month_res.groups()
pure_month_num = groups[1]
if pure_month_num:
month_num = int(number_translator(pure_month_num))
if 1 <= month_num <= 12:
month_res = '0' + str(month_num) if month_num < 10 else str(month_num)
month_st = this_year + '-' + '01-01'
month_ed = this_year + '-' + month_res + '-31'
return [month_st, month_ed]
# 前几个月 #!可能跨过年份 从上个月末往前推
before_month_res = re.search(before_month_num_rule, text)
if before_month_res:
before_month_group = before_month_res.groups()
if len(before_month_group) == 3:
pure_month_num = before_month_group[1]
shift_month = int(number_translator(pure_month_num)) if pure_month_num else 1
month_st = arrow.now().shift(months=-shift_month).format('YYYY-MM') + '-01'
month_ed = arrow.now().shift(months=-1).format('YYYY-MM') + '-31'
return [month_st, month_ed]
# 具体数字月份
specific_month_res = re.search(specific_month_num_rule, text)
if specific_month_res:
month_res = number_translator(specific_month_res.group())[:-1]
month_res = '0' + month_res if len(month_res) == 1 else month_res
month_st = this_year + '-' + month_res + '-01'
month_ed = this_year + '-' + month_res + '-31'
return [month_st, month_ed]
return []
except Exception:
traceback.print_exc()
return []
def week_trans(text: str) -> List:
"""周的转换, 返回一个时间段或时间点
`最近一周`等词, 从当天往前推算一周
`前三周`等词, 返回本周之前三个完整周
`n周前`, 返回当前时间往前推算n周的整个周
`n周后`, 返回大于当前时间往后推算n周的那天
不支持`某月第三周` , `某月前三周`等词语, 因为周的开始点不易确定
Args:
text (str): 输入文本
Returns:
List: 日期 或 周的开始和结束年月日
Example:
>>> week_trans('周三')
['=', '2021-07-14']
>>> week_trans('前三周')
['2021-06-21', '2021-07-11']
>>> week_trans('三周前')
['2021-06-21', '2021-06-27']
>>> week_trans('上周礼拜五')
['=', '2021-07-09']
"""
try:
# logger.debug(text)
# 先找到上周日, 再找到上上周日, 在它们的基础上做加减
week_today = arrow.now().weekday()
shift_day_from_last_sunday = week_today + 1
last_sunday_arrow = arrow.now().shift(days=-shift_day_from_last_sunday)
last_monday_arrow = last_sunday_arrow.shift(days=+1)
last_2_sunday_arrow = last_sunday_arrow.shift(days=-7)
# rule
#! 前后顺序有关系, 匹配范围更大, 更一般的放后面
recent_week_rule = r'(最近|近)([0-9一二两三四五六七八九十]+)(周)'
before_week_rule = r'(过去|前)([0-9一二两三四五六七八九十]+)(周)'
week_before_rule = r'([0-9一二两三四五六七八九十]+)(周前)'
week_after_rule = r'([0-9一二两三四五六七八九十]+)(周后)'
recent_weekday_rule = r'(上|上个|上一)+(周)+([1-7一二三四五六七])*'
this_weekday_rule = r'(这|这个|本)*(周)+([1-7一二三四五六七])*'
# 最近几周, 从今天开始往前推
recent_week_res = re.search(recent_week_rule, text)
if recent_week_res:
groups = recent_week_res.groups()
# print(groups)
if len(groups) == 3:
shift_num = int(number_translator(groups[1]))
week_st = arrow.now().shift(weeks=-shift_num).format('YYYY-MM-DD')
week_ed = arrow.now().format('YYYY-MM-DD')
return [week_st, week_ed]
# 前几周, 推到上一个周末
before_week_res = re.search(before_week_rule, text)
if before_week_res:
groups = before_week_res.groups()
# print(groups)
if len(groups) == 3:
shift_num = int(number_translator(groups[1]))
week_st = last_monday_arrow.shift(weeks=-shift_num).format('YYYY-MM-DD')
week_ed = last_sunday_arrow.format('YYYY-MM-DD')
return [week_st, week_ed]
# n周前/后
week_before_res = re.search(week_before_rule, text)
if week_before_res:
groups = week_before_res.groups()
shift_week = int(number_translator(groups[0]))
week_st = last_sunday_arrow.shift(weeks=-shift_week).shift(days=+1).format('YYYY-MM-DD')
week_ed = last_sunday_arrow.shift(weeks=-(shift_week-1)).format('YYYY-MM-DD')
return [week_st, week_ed]
week_after_res = re.search(week_after_rule, text)
if week_after_res:
groups = week_after_res.groups()
shift_week = int(number_translator(groups[0]))
week_day = arrow.now().shift(weeks=+shift_week).format('YYYY-MM-DD')
return ['>=', week_day]
# 上周某天/上周
recent_weekday_res = re.search(recent_weekday_rule, text)
if recent_weekday_res:
groups = recent_weekday_res.groups()
# print(groups)
if len(groups) == 3:
# 上周,上一周
if not groups[2]:
week_st = last_2_sunday_arrow.shift(days=+1).format('YYYY-MM-DD')
week_ed = last_2_sunday_arrow.shift(days=+7).format('YYYY-MM-DD')
return [week_st, week_ed]
# 上周二
else:
shift_num = int(number_translator(groups[2]))
week_day = last_2_sunday_arrow.shift(days=+shift_num).format('YYYY-MM-DD')
return ['=', week_day]
# 这周某天/这周
this_weekday_res = re.search(this_weekday_rule, text)
if this_weekday_res:
groups = this_weekday_res.groups()
# print(groups)
if len(groups) == 3:
# 本周, 周
if not groups[2]:
week_st = last_sunday_arrow.shift(days=+1).format('YYYY-MM-DD')
week_ed = last_sunday_arrow.shift(days=+7).format('YYYY-MM-DD')
return [week_st, week_ed]
# 周三, 本周三
else:
shift_num = int(number_translator(groups[2]))
week_day = last_sunday_arrow.shift(days=+shift_num).format('YYYY-MM-DD')
return ['=', week_day]
return []
except Exception:
traceback.print_exc()
return []
def day_trans(text: str, month_flag: bool = False) -> List:
"""日期的转换, 返回一个时间段或时间点
`最近n天`, `前n天` 等词, 均从当天往前推算到今天
`n天前`, 返回等于当前时间往前推算n天的那天
`n天后`, 返回大于当前时间往后推算n天的那天
`n号/日前`, 返回小于当月n-1号的那天
`n号/日后`, 返回大于当月n号的那天
Args:
text (str): 输入文本
month_flag (bool, optional): 日期前面是否有月份, 有的话在'前20天'这种处理会
变为当月的1-20天. Defaults to False.
Returns:
List: 日期 或 日期的开始和结束年月日
Example:
>>> day_trans('前五天')
['2021-07-08', '2021-07-13']
>>> day_trans('十八日')
['=', '2021-07-18']
>>> day_trans('五天前')
['=', '2021-07-08']
>>> day_trans('五号之前')
[('<=', '2021-07-04')]
"""
SPECIAL_DAY = ['大前天', '前天', '昨天', '今天', '明天', '后天', '大后天']
def special_day(text):
res_day = -1
today = arrow.now()
if '前天' in text:
res_day = today.shift(days=-2).format('YYYY-MM-DD')
if '大前天' in text:
res_day = today.shift(days=-3).format('YYYY-MM-DD')
if '昨天' in text:
res_day = today.shift(days=-1).format('YYYY-MM-DD')
if '今天' in text:
res_day = today.format('YYYY-MM-DD')
if '明天' in text:
res_day = today.shift(days=+1).format('YYYY-MM-DD')
if '后天' in text:
res_day = today.shift(days=+2).format('YYYY-MM-DD')
if '大后天' in text:
res_day = today.shift(days=+3).format('YYYY-MM-DD')
return res_day
try:
# logger.debug(text)
today_arrow = arrow.now()
# rule
recent_day_num_rule = r'(最近|近|前|这|过去)([0-9一二两三四五六七八九十]+)(天|日)' # `+`放里面才能匹配'九十'天
several_day_before_rule = r'([0-9一二两三四五六七八九十]+)(天)(前)'
several_day_after_rule = r'([0-9一二两三四五六七八九十]+)(天)(后)'
specific_day_before_rule = r'([0-9一二两三四五六七八九十]+)(号|日)(前)'
specific_day_after_rule = r'([0-9一二两三四五六七八九十]+)(号|日)(后)'
sepcial_day_rule = r'[前|昨|今|明|后]天'
specific_day_num_rule = r'([0-9一二两三四五六七八九十]+)(号|日)'
month_flag_day_rule = r'(偂)([0-9一二两三四五六七八九十]+)(天|日)'
# 特殊字符: 昨天等
for day in SPECIAL_DAY:
if day in text:
day_res = special_day(text)
return ['=', day_res]
# 特殊字符: 前n天, 前面有月份
month_flag_day_res = re.search(month_flag_day_rule, text)
if month_flag and month_flag_day_res:
groups = month_flag_day_res.groups()
pure_day_num = groups[1]
if pure_day_num:
pure_day_num = int(number_translator(pure_day_num))
if 1 <= pure_day_num <= 31: # 此处用arrow.replace 可能会报错
day_st = today_arrow.replace(day=1).format('YYYY-MM-DD')
day_ed = today_arrow.replace(day=pure_day_num).format('YYYY-MM-DD')
return [day_st, day_ed]
# 特殊字符: 前n天
recent_day_res = re.search(recent_day_num_rule, text)
if recent_day_res:
groups = recent_day_res.groups()
if len(groups) == 3:
pure_day_num = groups[1]
shift_day = int(number_translator(pure_day_num)) if pure_day_num else 1
day_st = today_arrow.shift(days=-shift_day).format('YYYY-MM-DD')
day_ed = today_arrow.format('YYYY-MM-DD')
return [day_st, day_ed]
# n天前/后
several_day_before_res = re.search(several_day_before_rule, text)
if several_day_before_res:
groups = several_day_before_res.groups()
shift_day = int(number_translator(groups[0]))
day = today_arrow.shift(days=-shift_day).format('YYYY-MM-DD')
return ['=', day]