簡體   English   中英

在 flask 的字符串列表中替換 substring

[英]replace substring in list of strings in flask

我正在使用 flask 和 pymongo 開展一個項目,我有一個用戶列表,其中用戶的實例如下:

user = {"Email":"user@gmail.com" , "Comments":["good" , "not very good " , "hated it "]}

我正在嘗試遍歷用戶集合中每個用戶的評論,如果在任何評論中找到string "good"我想用"bad"替換它。 在我的代碼下方,每次都會替換字符串,但不會保存在我的用戶集合中。

user_list = users.find()
for usr in user_list:
    for comment in usr['Comments']:
        if "good" in comment:
            print("old comment here")
            print(comment)
            comment=comment.replace("good" ,"bad") #does not save the edited comment in the collection !
            print(comment) # the new comment is printed

感謝您對這項簡單任務的幫助。 先感謝您。

如果您想保留當前的代碼結構,您將必須跟蹤您在 user_list 中的哪個位置以及哪個注釋。 然后你可以用新的評論來改變實際的評論。 一種方法是使用enumerate

user_list = [{"Email":"user@gmail.com" , "Comments":["good" , "not very good " , "hated it "]}]
for idxu, usr in enumerate(user_list):
    for idxc, comment in enumerate(usr['Comments']):
        if "good" in comment:
            print("old comment here")
            print(comment)
            user_list[idxu]['Comments'][idxc] = comment.replace("good" ,"bad") #does not save the edited comment in the collection !
            print(comment) # the new comment is printed

print(user_list)

>>> [{'Email': 'user@gmail.com', 'Comments': ['bad', 'not very bad ', 'hated it ']}]

如果您想將更改存儲在 mongodb 中,您當然必須將更改保存到用戶對象。

您只需要替換用戶評論,這在您的代碼中沒有完成。

for usr in user_list:
    usr["Comments"] = [i.replace("good", "bad") for i in usr["Comments"]]

例如。

user = {"Email":"user@gmail.com" , "Comments":["good" , "not very good " , "hated it "]}

user_list = [user]
print (user_list)

for usr in user_list:
    usr["Comments"] = [i.replace("good", "bad") for i in usr["Comments"]]

print (user_list)

OUTPUT:

[{'Email': 'user@gmail.com', 'Comments': ['good', 'not very good ', 'hated it ']}]
[{'Email': 'user@gmail.com', 'Comments': ['bad', 'not very bad ', 'hated it ']}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM