3

{[]} タグ内にデータを含むテキスト ファイルがあります。タグ内のデータを使用できるように、そのデータを解析するための推奨される方法は何ですか?

テキスト ファイルの例は次のようになります。

'これは{[本当に]}何の{[方法]}にも役立たないテキストの集まりです。いくつかのアイテムを {[get]} {[from]} ​​する必要があります。

'really'、'way'、'get'、'from' のリストで終わりたいと思います。私は分割を使用してそれを行うことができると思います..しかし、もっと良い方法があるようです。大量の解析ライブラリを見てきましたが、やりたいことに最適なものはありますか?

4

4 に答える 4

6

正規表現を使用します。この回答は、タグ文字 {}[] が他のタグ文字内に表示されないことを前提としています。

import re
text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'

for s in re.findall(r'\{\[(.*?)\]\}', text):
    print s

Python 正規表現で冗長モードを使用する:

re.findall('''
    \{   # opening curly brace
    \[   # followed by an opening square bracket
    (    # capture the next pattern
    .*?  # followed by shortest possible sequence of anything
    )    # end of capture
    \]   # followed by closing square bracket
    \}   # followed by a closing curly brace
    ''', text, re.VERBOSE)
于 2010-06-14T19:11:49.707 に答える
3

これは正規表現の仕事です:

>>> import re
>>> text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'
>>> re.findall(r'\{\[(\w+)\]\}', text)
['really', 'way', 'get', 'from']
于 2010-06-14T19:12:48.267 に答える
2

遅く、大きく、正規表現なし

古い学校のやり方 :P

def f(s):
    result = []
    tmp = ''
    for c in s:
        if c in '{[':
            stack.append(c)
        elif c in ']}':
            stack.pop()
            if c == ']':
                result.append(tmp)
                tmp = ''
        elif stack and stack[-1] == '[':
            tmp += c
    return result

>>> s
'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'
>>> f(s)
['really', 'way', 'get', 'from']
于 2010-06-15T08:18:07.990 に答える
1

別の方法

def between_strings(source, start='{[', end=']}'):
    words = []
    while True:
        start_index = source.find(start)
        if start_index == -1:
            break
        end_index = source.find(end)
        words.append(source[start_index+len(start):end_index])
        source = source[end_index+len(end):]
    return words


text = "this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it."
assert between_strings(text) == ['really', 'way', 'get', 'from']
于 2010-06-22T03:39:31.253 に答える