簡體   English   中英

從python括號中提取數據

[英]Extract data from within parenthesis in python

我知道有很多標題相同的問題。 我的情況有些不同。 我有一個像這樣的字符串:

"Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"

(注意,括號內嵌套了另一個括號)

我需要將其解析為嵌套字典,例如:

d["Cat"]["Money"] == 8
d["Cat"]["Points"] = 80
d["Mouse"]["Friends"]["Online"] == 10

等等。 我想在沒有庫和正則表達式的情況下執行此操作。 如果您選擇使用這些代碼,請詳細解釋代碼。 提前致謝!

編輯:

盡管這段代碼沒有任何意義,但這是我到目前為止的內容:

o_str = "Jake(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
spl = o_str.split("(")
def reverseIndex(str1, str2):
    try:
        return len(str1) - str1.rindex(str2)
    except Exception:
        return len(str1)
def app(arr,end):
    new_arr = []
    for i in range(0,len(arr)):
        if i < len(arr)-1:
            new_arr.append(arr[i]+end)
        else:
            new_arr.append(arr[i])
    return new_arr

spl = app(spl,"(")
ends = []
end_words = []
op = 0
cl = 0
for i in range(0,len(spl)):
    print i
    cl += spl[i].count(")")
    op += 1
    if cl == op-1:
        ends.append(i)
        end_words.append(spl[i])
        #break
    print op
    print cl
    print
print end_words

結束語是每個語句開頭的部分。 我計划使用遞歸來完成其余的工作。

現在,這很有趣。 你真的很討厭我這個...

def parse(tokens):
    """ take iterator of tokens, parse to dictionary or atom """
    dictionary = {}
    # iterate tokens...
    for token in tokens:
        if token == ")" or next(tokens) == ")":
            # token is ')' -> end of dict; next is ')' -> 'leaf'
            break
        # add sub-parse to dictionary
        dictionary[token] = parse(tokens)
    # return dict, if non-empty, else token
    return dictionary or int(token)

設置和演示:

>>> s = "Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
>>> tokens = iter(s.replace("(", " ( ").replace(")", " ) ").split())
>>> pprint(parse(tokens))
{'Cat': {'Friends': {'Offline': 8, 'Online': 0, 'Total': 8},
         'Money': 8,
         'Points': 80},
 'Mouse': {'Friends': {'Offline': 80, 'Online': 10, 'Total': 90},
           'Money': 10,
           'Points': 10000}}

另外,您還可以使用一系列字符串替換將其轉換為實際的Python字典字符串,然后對其進行求值,例如:

as_dict = eval("{'" + s.replace(")", "'}, ")
                       .replace("(", "': {'")
                       .replace(", ", ", '")
                       .replace(", ''", "")[:-3] + "}")

這會將'leaf'包裝在單例字符串集中,例如{'8'}而不是8 ,但這在后處理步驟中應該很容易解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM