【问题标题】:Cleaning up a certain level of a json file converted to a series清理某个级别的json文件转换为系列
【发布时间】:2021-02-23 21:59:22
【问题描述】:

我有一个特定级别的 json 文件,我已将其转换为 DF 中的系列。虽然这个级别有不同类型的消息,但我正在寻找一种尽可能最好的方式来清理这个系列的方法。下面,您可以看到我在该系列中的一条消息。

["Strategy B P-Q D-", {"type": "phone", "text": "21-01-30-20-12"}," (USDT_ANKR): deal_283850: Deal completed. Profit:  +13.", {"type": "phone", "text": "97856991"}," USDT (13.98 $) (3.14% from total volume (2.5% before trailing)) ????????????. ", {"type": "hashtag", "text": "#profit"}, " about 5 hours"]

这个LIST当然是这个json结构的表示:

   [
    "Strategy B P-Q D-",
    {
     "type": "phone",
     "text": "21-01-30-20-12"
    },
    " (USDT_ANKR): deal_283850: Deal completed. Profit:  +13.",
    {
     "type": "phone",
     "text": "97856991"
    },
    " USDT (13.98 $) (3.14% from total volume (2.5% before trailing)) ????????????. ",
    {
     "type": "hashtag",
     "text": "#profit"
    },
    " about 5 hours"
   ]

干净的信息很简单:

"Strategy B P-Q D-21-01-30-20-12 (USDT_ANKR): deal_283853127: Deal completed. Profit: +13.97856991 USDT (13.98 $) (3.14% from total volume (2.5% before trailing)) ???????????? #profit about 5 hours"

另一方面,并​​非所有消息都那么嘈杂。以下也是来自同一个 json 文件的消息之一。默认情况下它非常干净。

"GridBot (USDT_THETA): bot_346214: Grid line 4.556439 (4.556439) profit at the price of 2.18927"

目前,我正在转储这些 json 消息(将它们转换为字符串)并消除噪音(我已手动将其添加到列表中,如下所示:

noise = ['"]', '"}, "', ' {"', ' "', '", {"type": "phone", "text":']
df = df["messages"].str.replace('|'.join(noise), '', regex=True)

是否有更简洁的方法来做同样的事情 - 即清理嘈杂的内容以仅获取干净的消息 - 而不必手动创建包含所有噪声模式的列表并将它们从字符串中删除?

感谢您的帮助!

【问题讨论】:

    标签: python json python-3.x pandas


    【解决方案1】:

    由于您所有的“噪音”词典中都包含文本,因此与其尝试提​​取您不想要的文本,不如提取您想要的文本:

    value = [
        "Strategy B P-Q D-",
        {
            "type": "phone",
            "text": "21-01-30-20-12"
        },
        " (USDT_ANKR): deal_283850: Deal completed. Profit:  +13.",
        {
            "type": "phone",
            "text": "97856991"
        },
        " USDT (13.98 $) (3.14% from total volume (2.5% before trailing)) ???. ",
        {
            "type": "hashtag",
            "text": "#profit"
        },
        " about 5 hours"
    ]
    
    value = "".join([x if isinstance(x, str) else x["text"] for x in value])
    print(value)
    

    将输出:

    Strategy B P-Q D-21-01-30-20-12 (USDT_ANKR): deal_283850: Deal completed. Profit:  +13.97856991 USDT (13.98 $) (3.14% from total volume (2.5% before trailing)) ???. #profit about 5 hours
    

    【讨论】:

    • 谢谢!我认为这是要走的路,但是您如何将其应用于整个数据框列/功能?我尝试了一些不同的东西,但总是以TypeError: list indices must be integers or slices, not str
    • 没关系,我已经想通了。 df["messages"] = df["messages"].apply(lambda row: "".join([x if isinstance(x, str) else x["text"] for x in row]))。再次:谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2013-10-24
    • 2018-02-11
    相关资源
    最近更新 更多