我试图从文件中删除任何数字低于 -2000 的每一行。我对 python 很陌生,很可能我不理解该re模块,也不确定我正在使用的方法。
这是示例文件:
{ "Position": { "X": -1660.313, "Y": -3107.795, "Z": 12.85458 }
{ "Position": { "X": -494.0083, "Y": 57.33647, "Z": 56.59263 }
{ "Position": { "X": -1039.662, "Y": -2641.444, "Z": 36.96656 }
Run Code Online (Sandbox Code Playgroud)
这是我得到的:
with open('file.json','r') as input:
with open("temp.json", 'w') as output:
for line in input:
match = re.search(r'('-'\d+)', line)
my_number = float(match.group())
if my_number < -2000:
output.write(line.strip())
Run Code Online (Sandbox Code Playgroud)
就目前而言,我确信re.search(r'('-'\d+)),'-'是错误的。我也不确定如何正确使用match.group().
如果有人能指导我正确的方向或提出不同的方法,我将不胜感激。
不要使用正则表达式。将该行解析为 JSON 并进行测试。
with open('file.json','r') as input, open("temp.json", 'w') as output:
for line in input:
d = json.loads(line)
if all(x >= -2000 for x in d['Position'].values()):
output.write(line)
Run Code Online (Sandbox Code Playgroud)
另外,不要写line.strip()。这将删除换行符,因此输出文件将在一个长行上包含所有内容,而不是像输入文件那样为每个项目单独一行。
此答案假设您在将这些行复制到问题中时犯了错误。要成为有效的 JSON,这些行必须类似于:
{ "Position": { "X": -1660.313, "Y": -3107.795, "Z": 12.85458 } }
Run Code Online (Sandbox Code Playgroud)
}最后有第二个。