MCPcopy Create free account
hub / github.com/PaddlePaddle/Research / tokenize

Function tokenize

NLP/Text2SQL-BASELINE/text2sql/utils/dusql_evaluation.py:89–150  ·  view source on GitHub ↗

Args: Returns:

(string)

Source from the content-addressed store, hash-verified

87
88#################################
89def tokenize(string):
90 """
91 Args:
92
93 Returns:
94 """
95 string = string.replace("\'", "\"").lower()
96 assert string.count('"') % 2 == 0, "Unexpected quote"
97
98 def _extract_value(string):
99 """extract values in sql"""
100 fields = string.split('"')
101 for idx, tok in enumerate(fields):
102 if idx % 2 == 1:
103 fields[idx] = '"%s"' % (tok)
104 return fields
105
106 def _resplit(tmp_tokens, fn_split, fn_omit):
107 """resplit"""
108 new_tokens = []
109 for token in tmp_tokens:
110 token = token.strip()
111 if fn_omit(token):
112 new_tokens.append(token)
113 elif re.match(r'\d\d\d\d-\d\d(-\d\d)?', token):
114 new_tokens.append('"%s"' % (token))
115 else:
116 new_tokens.extend(fn_split(token))
117 return new_tokens
118
119 tokens_tmp = _extract_value(string)
120
121 two_bytes_op = ['==', '!=', '>=', '<=', '<>', '<in>']
122 sep1 = re.compile(r'([ \+\-\*/\(\),><;])') # 单字节运算符
123 sep2 = re.compile('(' + '|'.join(two_bytes_op) + ')') # 多字节运算符
124 tokens_tmp = _resplit(tokens_tmp, lambda x: x.split(' '), lambda x: x.startswith('"'))
125 tokens_tmp = _resplit(tokens_tmp, lambda x: re.split(sep2, x), lambda x: x.startswith('"'))
126 tokens_tmp = _resplit(tokens_tmp, lambda x: re.split(sep1, x),
127 lambda x: x in two_bytes_op or x.startswith('"'))
128 tokens = list(filter(lambda x: x.strip() not in ('', 'distinct', 'DISTINCT'), tokens_tmp))
129 def _post_merge(tokens):
130 """merge:
131 * col name with "(", ")"
132 * values with +/-
133 """
134 idx = 1
135 while idx < len(tokens):
136 if tokens[idx] == '(' and tokens[idx - 1] not in EXPECT_BRACKET_PRE_TOKENS:
137 while idx < len(tokens):
138 tmp_tok = tokens.pop(idx)
139 tokens[idx - 1] += tmp_tok
140 if tmp_tok == ')':
141 break
142 elif tokens[idx] in ('+', '-') and tokens[idx - 1] in COND_OPS and idx + 1 < len(tokens):
143 tokens[idx] += tokens[idx + 1]
144 tokens.pop(idx + 1)
145 idx += 1
146 else:

Callers 1

get_sqlFunction · 0.70

Calls 5

countMethod · 0.80
_extract_valueFunction · 0.70
_resplitFunction · 0.70
_post_mergeFunction · 0.70
replaceMethod · 0.45

Tested by

no test coverage detected