【问题标题】:Dynamically remove substring from string从字符串中动态删除子字符串
【发布时间】:2021-05-30 22:52:39
【问题描述】:

我有一个有点直截了当的困境,但我无法找到解决方案。

我从 MongoDB 数据库中获取一个 JSON 文件并使用json.dumps 将其转换为字符串:

client = MongoClient("XXXX")
db = client.testdb
table = db.testingtable
document = table.find()
document = list(document)
docs = json.dumps(document,default=str)
print(docs)

电流输出:

[{"_id": "67", "userId": 167, "productID": "Reference('product_id', ObjectId('5f4523b893d7b757bcbd2d71'))"}]

我将如何动态在整个字符串中搜索单词Reference,如果找到,它应该删除除了括号内的字母数字值之外的所有内容没有这样做:

docs.replace("Reference('product_id', ObjectId('",'').replace("'))",'')

预期输出:

[{"_id": "67", "userId": 167, "productID": "5f4523b893d7b757bcbd2d71"}]

【问题讨论】:

    标签: python regex pandas substring


    【解决方案1】:
    from pandas.io.json import json_normalize
    df=pd.json_normalize([{"_id": "67", "userId": 167, "productID": "Reference('product_id', ObjectId('5f4523b893d7b757bcbd2d71'))"}])#convert to df
    
    
    #Using regex, extract string between `ObjectId(`and  `)` and turn it back to json
    df.assign(productID=df.productID.str.extract('(?<=ObjectId\()(.*?)(?=\))')).to_json(orient="records")
    
    
    [{"_id":"67","userId":167,"productID":"'5f4523b893d7b757bcbd2d71'"}]
    

    【讨论】:

    • 这是一个很好的解决方案,但是,我会说它是部分动态的,因为它假定 objectId 将始终驻留在 productId 列中,因此如果 objectId 在例如userId 列不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多