我在數百個看起來像這樣的檔案上有數百個條目(數字不固定):
"DstQuad":[12,-36,27,-36,27,-23,12,-23],"SrcQuad":[493,95,508,95,508,108,493,108]
檔案的相關部分看起來像這樣,重復了數百次,沒有行,只有一個連續的字串:
{"TexID":0,"DstQuad":[-24,-23,-1,-23,-1,6,-24,6],"SrcQuad":[61,240,84,240,84,269,61,269]},{"TexID":0,"DstQuad":[-11,-73,36,-73,36,-45,-11,-45],"SrcQuad":[87,240,134,240,134,268,87,268]},
我需要能夠判斷一個數字何時在該結構內,然后取每個數字并將其相乘,同時不將數字單獨留在該結構中。
嘗試改編我發現的腳本,但它沒有做任何事情:
def multiply_numbers_in_context(match):
# return "{0}{1}{2}".format(match.group(1), str(float(match.group(2))*4), '"')
return "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}".format(match.group(1), str(int(match.group(2))*4), ',', str(int(match.group(3))*4), ',', str(int(match.group(4))*4), ',', str(int(match.group(5))*4), ',', str(int(match.group(6))*4), ',', str(int(match.group(7))*4), ',', str(int(match.group(8))*4), ',', str(int(match.group(9))*4), ',', match.group(10), ',', str(int(match.group(11))*4), ',', str(int(match.group(12))*4), ',', str(int(match.group(13))*4), ',', str(int(match.group(14))*4), ',', str(int(match.group(15))*4), ',', str(int(match.group(16))*4), ']')
editor.rereplace(r'("DstQuad":[)(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d )(],"SrcQuad":[)(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d ),(-?\d )(])', multiply_numbers_in_context)
幫助將不勝感激。
uj5u.com熱心網友回復:
我建議json為此使用該模塊。這是一個簡單的例子,它加載了一個 JSON 字串并使用object_hook一個常量值(在本例中為 4)乘以每個串列元素。結果string是一個 JSON 字串,然后可以將其保存到檔案中。
我還對您的用例做了一些假設:
- 檔案的內容可以表示為一個串列
[],其中包含一堆{}帶有有用資料的字典 - 所有
[]包含數字的嵌套串列都應將其所有元素乘以一個常數值(在本例中為 4)
import json
file_contents = """
[
{"TexID":0,"DstQuad":[-24,-23,-1,-23,-1,6,-24,6],"SrcQuad":[61,240,84,240,84,269,61,269]},
{"TexID":0,"DstQuad":[-11,-73,36,-73,36,-45,-11,-45],"SrcQuad":[87,240,134,240,134,268,87,268]}
]
"""
def hook_fn(value, multiplier=4):
if isinstance(value, list) and value and isinstance(value[0], (int, float)):
return [elem * multiplier for elem in value]
if isinstance(value, dict):
return {k: hook_fn(v) for k, v in value.items()}
return value
string = json.dumps(json.loads(file_contents, object_hook=hook_fn))
print(string)
# [{"TexID": 0, "DstQuad": [-96, -92, -4, -92, -4, 24, -96, 24], "SrcQuad": [244, 960, 336, 960, 336, 1076, 244, 1076]}, {"TexID": 0, "DstQuad": [-44, -292, 144, -292, 144, -180, -44, -180], "SrcQuad": [348, 960, 536, 960, 536, 1072, 348, 1072]}]
要從文本檔案中讀取和寫入,請使用json.loadandjson.dump代替(s在末尾洗掉):
with open('input.txt') as in_file:
data = json.load(in_file, object_hook=hook_fn)
with open('output.txt', 'w') as out_file:
json.dump(data, out_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310934.html
上一篇:為什么不能用它的鍵呼叫字典的值?
