繁体   English   中英

使用正则表达式PYTHON替换文件中的特定字符串

[英]Replacing a specific string in a file using regex PYTHON

我正在使用Stanford NER标记文件,并且希望将每个“ O”标记替换为“ NONE”。 我已经尝试过此代码,但是显示错误的输出。 问题是它替换了字符串中的每个“ 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

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

您不需要遍历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或行$的结尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM