File size: 1,472 Bytes
29439fe | 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 | """Chinese spoken-form normalization, preserving serial/card digit readings."""
import re
from wetext.wetext import normalize
DIGITS=str.maketrans('0123456789','零一二三四五六七八九')
SERIAL=re.compile(r'(订单(?:编)?号?|单号|编号|受理号|流水号|工单号|运单号|快递单号|航班(?:号)?|票号)([是为]?[::]?\s*)([A-Za-z]{0,4})([0-9][0-9]{3,})')
CARD=re.compile(r'((?:卡号[^0-9,。!?,!?]{0,8}四位|末四位|最后四位|尾号)[是为::\s]*)([0-9]{4})(?![0-9.])')
FLIGHT=re.compile(r'(?<![A-Za-z])([A-Za-z]{2})([0-9]{3,4})(?=\s*航班)')
PUNCT=str.maketrans(',!?;:',',!?;:')
def normalize_text(text):
text=text.strip().replace('\r','').replace('\n','。').replace('\t',' ')
text=SERIAL.sub(lambda m:m[1]+m[2]+m[3]+m[4].translate(DIGITS),text)
text=CARD.sub(lambda m:m[1]+m[2].translate(DIGITS),text)
text=FLIGHT.sub(lambda m:m[1]+m[2].translate(DIGITS),text)
text=normalize(text,lang='zh')
output=[]
for i,char in enumerate(text):
if char=='.':
previous=text[i-1] if i else ''
following=text[i+1] if i+1<len(text) else ''
if previous.isdigit() and following.isdigit() or previous.isascii() and previous.isalpha() and following.isascii() and following.isalpha():
output.append(char)
else:
output.append('。')
else:
output.append(char.translate(PUNCT))
return ''.join(output)
|