使用regex PYTHON替换文件中的特定字符串

2024-09-25 00:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Stanford NER标记一个文件,我想用“NONE”替换每个“O”标记。我已经尝试过这个代码,但它显示错误的输出。问题是它会替换字符串中的每个“O”。我不熟悉正则表达式,不知道什么是适合我的问题正则表达式。蒂亚

Here's my code:

    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))

Sample Input:

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

OUTPUT:

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

Tags: textin标记renoneforstringtype
1条回答
网友
1楼 · 发布于 2024-09-25 00:28:46

您不需要在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

这里\bO(?=\n|$)匹配单个字母O,后跟新行字符\n或行尾$

相关问题 更多 >