Luigi commited on
Commit
32c85a9
·
verified ·
1 Parent(s): 41a550e

text_norm: time-of-day + decimals

Browse files
Files changed (1) hide show
  1. scripts/text_norm.py +22 -0
scripts/text_norm.py CHANGED
@@ -52,6 +52,20 @@ def normalize(text: str) -> str:
52
  return " " + re.sub(r"\s+", " ", s).strip() + " "
53
  text = re.sub(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}", email, text)
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  # 2) DATE zh 2024年3月15日 / en mixes
56
  def date_zh(m):
57
  y, mo, d = m.group(1), m.group(2), m.group(3)
@@ -114,6 +128,14 @@ def normalize(text: str) -> str:
114
  return " " + " ".join((_EN[c] if c.isdigit() else c.upper()) for c in s if c.isalnum()) + " "
115
  text = re.sub(r"\b(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)[A-Za-z0-9]{2,}(?:-[A-Za-z0-9]+)*\b", serial, text)
116
 
 
 
 
 
 
 
 
 
117
  # 8) COUNTS / remaining standalone digit runs
118
  def num(m):
119
  d = m.group(0); en = _en_ctx(text, m.start(), m.end()); after = text[m.end():m.end()+1]
 
52
  return " " + re.sub(r"\s+", " ", s).strip() + " "
53
  text = re.sub(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}", email, text)
54
 
55
+ # 1.5) TIME of day 9:30 / 3:15 PM / 14:30 (needs :MM so ratios like 3:2 are untouched)
56
+ def time_repl(m):
57
+ h, mm, ap = int(m.group(1)), m.group(2), m.group(3)
58
+ mi = int(mm); en = _en_ctx(text, m.start(), m.end())
59
+ if en:
60
+ hh = _card_en(h)
61
+ t = f"{hh} o'clock" if mi == 0 else (f"{hh} oh {_card_en(mm)}" if mi < 10 else f"{hh} {_card_en(mm)}")
62
+ if ap: t += " " + ("a m" if 'a' in ap.lower() else "p m")
63
+ return " " + t + " "
64
+ pre = ("上午" if 'a' in ap.lower() else "下午") if ap else ""
65
+ t = f"{pre}{_card_zh(str(h))}點" + ("整" if mi == 0 else ("半" if mi == 30 else _card_zh(mm) + "分"))
66
+ return " " + t + " "
67
+ text = re.sub(r"\b(\d{1,2}):(\d{2})(?::\d{2})?\s*([AaPp][.]?[Mm][.]?)?\b", time_repl, text)
68
+
69
  # 2) DATE zh 2024年3月15日 / en mixes
70
  def date_zh(m):
71
  y, mo, d = m.group(1), m.group(2), m.group(3)
 
128
  return " " + " ".join((_EN[c] if c.isdigit() else c.upper()) for c in s if c.isalnum()) + " "
129
  text = re.sub(r"\b(?=[A-Za-z0-9-]*[A-Za-z])(?=[A-Za-z0-9-]*\d)[A-Za-z0-9]{2,}(?:-[A-Za-z0-9]+)*\b", serial, text)
130
 
131
+ # 7.5) DECIMALS 12.5 -> 十二點五 / twelve point five (avoid IPs/versions a.b.c)
132
+ def dec_repl(m):
133
+ whole, frac = m.group(1), m.group(2)
134
+ if _en_ctx(text, m.start(), m.end()):
135
+ return f" {_card_en(whole)} point {' '.join(_EN[c] for c in frac)} "
136
+ return f" {_card_zh(whole)}點{''.join(_ZH[c] for c in frac)} "
137
+ text = re.sub(r"(?<![\d.])(\d+)\.(\d+)(?![\d.])", dec_repl, text)
138
+
139
  # 8) COUNTS / remaining standalone digit runs
140
  def num(m):
141
  d = m.group(0); en = _en_ctx(text, m.start(), m.end()); after = text[m.end():m.end()+1]