我正在使用斯坦福 NER 标记一个文件,我想用“NONE”替换每个“O”标签。我已经尝试过这段代码,但它显示了错误的输出。问题是它替换了字符串中的每个“O”。我不熟悉正则表达式,也不知道什么是适合我的问题的正则表达式。TIA。
这是我的代码:
import re
tagged_text = st.tag(per_word(input_file))
string_type = "\n".join(" ".join(line) for line in tagged_text)
for line in string_type:
output_file.write (re.sub('O$', 'NONE', line))
样本输入:
Tropical O
Storm O
Jolina O
affects O
2,000 O
people O
MANILA LOCATION
, O
Philippines LOCATION
– O
Initial O
reports O
from O
the O
输出:
Tropical NONE
Storm NONE
Jolina NONE
affects NONE
2,000 NONE
people NONE
MANILA LNONECATINONEN
, NONE
Philippines LNONECATINONEN
– NONE
Initial NONE
reports NONE
from NONE
the NONE
您不需要循环string_type
,re.sub
直接在字符串上使用应该可以:
s = """Tropical O
Storm O
Jolina O
affects O
2,000 O
people O
MANILA LOCATION
, O
Philippines LOCATION
– O
Initial O
reports O
from O
the O"""
import re
print(re.sub(r"\bO(?=\n|$)", "NONE", s))
给出:
Tropical NONE
Storm NONE
Jolina NONE
affects NONE
2,000 NONE
people NONE
MANILA LOCATION
, NONE
Philippines LOCATION
– NONE
Initial NONE
reports NONE
from NONE
the NONE
Here\bO(?=\n|$)
匹配单个字母O
后跟换行符\n
或行尾$
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句