2017-10-14 2 views
0

私はスタンフォードNERを使ってファイルにタグを付けるので、すべての "O"タグを "NONE"に置き換えたい。私はすでにこのコードを試しましたが、出力が間違っています。問題は、文字列のすべての "O"を置き換えることです。私は正規表現に慣れていないと私の問題のための正しい正規表現がわからない。 TIA。regexを使ってファイル内の特定の文字列を置き換えるPYTHON

ここに私のコードです:

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 
+0

'string_type'とは何ですか?あなたは文字で確認している文字列をループしているようです。 – Psidom

+0

@Psidom tagged_text(タプル)を文字列(string_type)に変換し、行ごとに読み込みました。 –

+0

どのインスタンスで失敗していますか。たとえば、試してみました 'line = 'TrOpical O' re.sub( 'O $'、 'NONE'、行) ' ' TrOpical NONE ' – chakri

答えて

1

あなたは動作するはずの文字列に直接re.subを使用し、string_typeをループする必要はありません。

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または末尾が$のいずれかです。

関連する問題