2

以下の形式のデータがあります。

<a> <b> <c> <This is a string>
<World Bank> <provides> <loans for> <"a Country's Welfare">
<Facebook> <is a> <social networking site> <"Happy Facebooking => Enjoy">

ここで、区切り文字 <> に基づいて上記の各行を分割したいと思います。つまり、次のように分割します。

['<a>', '<b>', '<c>', '<This is a string>']
['<World Bank>', '<provides>', '<loans for>', '<"a Country\'s Welfare">']
['<Facebook>', '<is a>', '<social networking site>', '<"Happy Facebooking => Enjoy">']

スペースと "> " に基づいて分割しようとしましたが、うまくいきません。上記の方法で分割できるPythonの他の方法はありますか。私のファイル サイズは 1 TB であるため、手動で行うことはできません。

4

2 に答える 2

0

これは、一種の「独自のパーサーを構築する」アプローチであり、ファイルを文字ごとに処理するだけで、派手な正規表現機能は使用しません。

def tag_yielder(line):
    in_tag = False
    escape = False
    current_tag = ''
    for char in line:
        if in_tag:
            current_tag += char
            if char == '>' and not escape:
                yield current_tag
                current_tag = ''
                in_tag = False
            if char == '=':
                escape = True
            else:
                escape = False
        else:
            if char == '<':
                current_tag = '<'
                in_tag = True

for line in open('tag_text.txt'):
    print([tag for tag in tag_yielder(line.strip())])

出力:

['<a>', '<b>', '<c>', '<This is a string>']
['<World Bank>', '<provides>', '<loans for>', '<"a Country\'s Welfare">']
['<Facebook>', '<is a>', '<social networking site>', '<"Happy Facebooking => Enjoy">']
于 2013-05-22T23:34:33.237 に答える