从文本文件中解析项目

时间:2010-06-14 19:07:45

标签: python string text-processing

我有一个文本文件,其中包含{[]}标记内的数据。解析数据的建议方法是什么,以便我可以只使用标记内的数据?

示例文本文件如下所示:

'这是一堆在任何{[way]}中都没有{[really]}有用的文本。我需要{[get]}一些项目{[from]}。“

我想在列表中以“真实”,“方式”,“获取”,“来自”结束。我想我可以用split来做它..但似乎可能有更好的方法。我看过很多解析库,有没有一个对我想做的事情很完美?

4 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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']

答案 2 :(得分: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']

答案 3 :(得分: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']