【问题标题】:Extracting data after filtering substring using Python使用Python过滤子字符串后提取数据
【发布时间】:2018-11-22 13:30:25
【问题描述】:

我有一个这种格式的 DNS 流量 JSON 文件

{
    "index": {
        "_type": "answer_query", 
        "_id": 0, 
        "_index": "index_name"
    }
}

{
    "answer_section": " ", 
    "query_type": "A", 
    "authority_section": "com. 172 IN SOA a.xxxx-xxxx.net. nstld.xxxx-xxxxcom. 1526440480 1800 900 604800 86400", 
    "record_code": "NXDOMAIN", 
    "ip_src": "xx.xx.xx.xx", 
    "response_ip": "xx.xx.xx.xx", 
    "date_time": "2018-05-16T00:57:20Z", 
    "checksum": "CORRECT", 
    "query_name": "xx.xxxx.com.", 
    "port_src": 50223, 
    "question_section": "xx.xxxx.com. IN A", 
    "answer_count_section": 0
}

我需要提取authority_section中空格后面的数字(在示例中为172)小于300的数据,忽略不符合要求的数据,然后将输出写入另一个JSON 文件。

我怎样才能做到这一点?谢谢

【问题讨论】:

  • 显示你的尝试。
  • 还为这种情况下的预期输出 (JSON) 编写一个示例。
  • @l'L'l 我对使用 Python 还是很陌生,所以我还没有任何像样的代码。
  • @Hemant_Negi 输出应该和输入的JSON文件有类似的结构,只有300以上的数据会被删除。

标签: python split substring


【解决方案1】:

假设 stack1.txt 是您发布的文件。这将写入一个新文件 stack2.txt,如果“空格后的值”> = 300,则省略“authority_section”行。此解决方案不需要解析 json,但它非常依赖于数据的格式一致。

import os
with open('stack2.txt','w') as new_file:
    old_file = open('stack1.txt').readlines()
    delete_file = False
    for line in old_file:
        if not (line.strip().startswith('"authority_section"') and int(line.split(':')[1].split()[1]) >= 300):
            new_file.write(line)
        else:
            delete_file = True
if delete_file:
    os.remove('stack2.txt')

【讨论】:

  • 感谢您的回复!这确实写入了另一个与输入具有相似结构的文件,但我仍然拥有值高于 300 的数据。我不确定是否是这种情况,但过滤器是否应该在第二个空格之后“authority_section”行?
  • 当我更改 172 --> 304 时,它会在新文件中省略该行,正如预期的那样。如果你不能指望你的数据格式是一致的,那么使用正则表达式可能是一个更好的答案......
  • 啊抱歉,我的意思是我想过滤那些值
  • 之后删除文件? ^
【解决方案2】:

你可以试试这样的:

#!/usr/bin/python3
import json
import re

data = (
    """
    {
         "answer_section": " ",
         "query_type": "A",
         "authority_section": "com. 172 IN SOA a.xxxx-xxxx.net. nstld.xxxx-xxxxcom. 1526440480 1800 900 604800 86400",
         "record_code": "NXDOMAIN",
         "ip_src": "xx.xx.xx.xx",
         "response_ip": "xx.xx.xx.xx",
         "date_time": "2018-05-16T00:57:20Z",
         "checksum": "CORRECT",
         "query_name": "xx.xxxx.com.",
         "port_src": 50223,
         "question_section": "xx.xxxx.com. IN A",
         "answer_count_section": 0
    }
    """
)


json_data = json.loads(data)
print('BEFORE: ', json_data)

r = re.compile('^\s([1-2]\d\d|[1-9]\d|[1-9])\s$')


found = False
key_to_delete = None

for key, value in json_data.items():
    if value == 0:
        pass
    else:
        tmp = str(value)
        for i in range(0, len(tmp)):
            if r.match(tmp[i:i+3]):
                found = True
                key_to_delete = key
                print('FOUND 1: ', value)
            elif r.match(tmp[i:i+4]):
                found = True
                key_to_delete = key
                print('FOUND 2: ', value)
            elif r.match(tmp[i:i+5]):
                found = True
                key_to_delete = key
                print('FOUND 3: ', value)

if found:
    json_data.pop(key_to_delete)

print('RESULT: ', json_data)

我在回答中使用了正则表达式。阅读正则表达式了解更多详情。

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2020-04-18
    相关资源
    最近更新 更多