我有一個看起來像這樣的 JSON 字串
[{"25":"Fresh Vegetable Platter with Olive Oil Dip "},{"23":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"26":"Mexican Pineapple Salad "},{"28":"Saut\u00e9ed Savoy Cabbage with Scallions and Garlic "},{"24":"Braised Escarole with Currants and Pine Nuts "}]
我想用單詞標題替換數字,但是“Saut\u00e9ed”部分中的數字會導致問題,因為我想保持這種方式。
我努力了:
recommendations = re.sub('\d', 'title', recommendations)
這給了我這個:
[{"titletitle":"Fresh Vegetable Platter with Olive Oil Dip "},{"titletitle":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"titletitle":"Mexican Pineapple Salad "},{"titletitle":"Saut\utitletitleetitleed Savoy Cabbage with Scallions and Garlic "},{"titletitle":"Braised Escarole with Currants and Pine Nuts "}]
uj5u.com熱心網友回復:
如果您更換:
recommendations = re.sub('\d', 'title', recommendations)
和
recommendations = re.sub('\d ', 'title', recommendations)
它應該作業。
告訴正 則運算式匹配“至少一個(但可能更多)數字”。
為了將來在正則運算式中參考,您可以使用這些字符來指示要匹配的特定數量:
?0 或 1 次出現1 次或多次出現*任意數量的出現(包括零)
uj5u.com熱心網友回復:
嘗試:
recommendations = re.sub(r'\d ','title', recommendations )
uj5u.com熱心網友回復:
鑒于您希望“Saut\u00e9ed”不受影響,這里有一個有趣的串列理解:
a = [{"25":"Fresh Vegetable Platter with Olive Oil Dip "},{"23":"Ginger-Lime Coconut Cake with Marshmallow Frosting "},{"26":"Mexican Pineapple Salad "},{"28":"Saut\u00e9ed Savoy Cabbage with Scallions and Garlic "},{"24":"Braised Escarole with Currants and Pine Nuts "}]
b = [{'title': list(i.values())[0]} for i in a]
uj5u.com熱心網友回復:
recommendations = re.sub(r'"\d "', '"title"', recommendations)
這行得通,這只會替換包裹在“”中的數字
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453614.html
