[英]tokenize sentence into specific words in python
我正在使用 crf model 来识别句子中的单词(ner),我正在使用这段代码,除了标记化之外,一切都很好:
sentence = '<174>Jan 18 18:20:37 test : 10.0.0.0 - - [18/Jan/2019:18:20:37 +0100] "POST /Test/tt/Test/t_page1.html HTTP/1.0" 404 146 "-" " Mozilla/X.X [en] (X11, U; Test-VT 2.0.2) "'
re_tok = re.compile(f"([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])")
sentence = re_tok.sub(r" ", sentence).split()
padded_sentence = sentence + [word2index["--PADDING--"]] * (MAX_SENTENCE - len(sentence))
padded_sentence = [word2index.get(w, 0) for w in padded_sentence]
pred = ner_model.predict(np.array([padded_sentence]))
pred = np.argmax(pred, axis=-1)
retval = ""
for w, p in zip(sentence, pred[0]):
retval = retval + "{:15}: {:5}".format(w, index2tag[p])+ "\n"
print(retval)
我把它当作 output:
174 : O
Jan : MONTH
18 : DAY
18 : O
20 : O
37 : O
test : HOSTNAME
10 : O
0 : O
0 : O
0 : O
18 : DAY
Jan : MONTH
2019 : O
18 : O
20 : O
37 : O
0100 : O
POST : METHOD
Test : O
tt : O
Test : O
t : O
page1 : O
html : O
HTTP : O
1 : O
0 : O
404 : O
146 : O
Mozilla : O
但这不是我真正想要的,我想要这样的 output:
Jan : MONTH
18 : Day
18:20:37 : Time
Test : O
10.0.0.0 : IP
18/Jan/2019:18:20:37 : TIMESTAMP
POST : METHOD
/Test/tt/Test/t_page1.html : PATH
HTTP/1.0 : HTTP_VERSION
404 : O
146 : O
Mozilla/X.X [en] (X11, U; Test-VT 2.0.2) : USER_AGENT
有没有人可能知道如何解决这个问题
您需要在包含它之前重新string.punctuation
re.escape
因为它包含各种控制字符
- re.compile(f"([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])")
+ re.compile(f"([{re.escape(string.punctuation)}“”¨«»®´·º½¾¿¡§£₤‘’])")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.