【问题标题】:replace substring in list of strings in flask替换烧瓶中字符串列表中的子字符串
【发布时间】:2020-06-23 19:25:35
【问题描述】:

我正在使用烧瓶和 pymongo 开展一个项目,并且我有一个用户列表,其中用户实例如下:

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

我正在尝试遍历我的用户集合中每个用户的 cmets,如果我在任何评论中找到 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

感谢您对这项简单任务的帮助。 提前谢谢你。

【问题讨论】:

  • 您正在更改 for 循环中的变量注释,而不是列表中的值。

标签: python string mongodb replace pymongo


【解决方案1】:

如果您想保留当前的代码结构,您将必须跟踪您在 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 中,您当然必须将更改保存到用户对象。

【讨论】:

  • 我有 user_list = users.find()
  • 我进入 user_list[idxu]['Comments'][idxc] = comment.replace("good" ,"bad") pymongo.errors.InvalidOperation: 执行查询后无法设置选项跨度>
【解决方案2】:

您只需要替换用户 cmets,这在您的代码中没有完成。

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)

输出:

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

【讨论】:

  • 没用。可能代码有问题
  • 我有 user_list = users.find() 不仅仅是一个用户
  • 您只需将我的代码中的 3 替换为您可能喜欢的任何用户列表:D
  • 我得到 'usr' 不支持 usr['Comments'] 中的项目分配。我也做了 user_list = [users.find()]
猜你喜欢
  • 2017-06-22
  • 2019-06-26
  • 2019-11-08
  • 2021-05-22
  • 2018-06-02
  • 2021-12-19
  • 2012-04-03
  • 2013-07-23
相关资源
最近更新 更多