0

このようなテキスト/文字列があるとしましょう

This is something before any tag, today's date is 09-06-2012 blah blah
<firsttag> content of first tag </firsttag> <sentence> This is the
first sentence in my paragraph that needs to be <bold> displayed.
</bold> </sentence> <secondtag> blah blah blah <italics> another blah
</italics></secondtag> <sentence> This is the second sentence in my
paragraph that needs to be displayed and it has some weird contents
like \n\n\n and inbetween reference tags like <link> http://google.com
</link></sentence> <thirdtag>blah blah </thirdtag><sentence>Tennis is
a great sport, I'm really sad that <link
synthetic="True"><target>Roger Federer </link></target>Roger Federer
lost yesterday.</sentence>

出力は次のようになります

これは、表示する必要がある段落の最初の文です。これは、表示する必要がある段落の 2 番目の文であり、次のような奇妙な内容が含まれています。ロジャー フェデラーは昨日負けました。

正規表現解析後の私の出力は、内部のコンテンツとタグのみである必要があります。「Roger Federer」の場合のように、すべてのタグ、奇妙な \n\n 文字、内部のすべてのジャンク コンテンツを削除する必要があります。これは Freebase-wiki (WEX) であるため、リンクは単に Roger Federer のページを指しているだけです。私が扱っているデータセット。この問題を解決するのに役立つ単純な python re コードは非常に役立ちます。私が試しているコードはこのようなものです。

for line in fileinput.input():
        p = re.sub('<[^>]*>', '', line)
        p = re.sub('\n','',p)
print p

私は巨大なファイルを扱っているので、map-reduce (hadoop) コードで私を助けてくれれば、それも非常に役に立ちます。前もって感謝します :)

4

1 に答える 1

1

私はあなたの問題のためのカスタムソリューションをいじくり回しました. パラメータとして文字列を入力する必要がありますs

def convert_with_regex(s):
    sents = re.compile(r"<sentence>(.*?)</sentence>", re.S)
    fin = re.compile(r"<(.*)>(.*?)</.*>|[\n]+", re.S)
    result=[]
    for sent in sents.findall(s.replace("<bold>","").replace("</bold>","")):
        result.append(fin.sub("",sent))
    return ''.join(result)

それほどエレガントではないことはわかっていますが、「フォームは機能に従います」:)

于 2012-09-06T20:38:47.563 に答える