微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:即使绝对存在,也不会在列表中找到字符串

如何解决Python:即使绝对存在,也不会在列表中找到字符串

这应该是一个简单的问题,但它使我发疯。当我在字符串列表中搜索关键字“ gift”时,只要手动设置字符串“ gift”,python就会找到它。当我从字典键派生字符串时,即使dict键是一个没有错别字的相同字符串对象,python也不会在相关列表中找到它。这是确切的代码

这项工作:

subtopic_keys = list(copy.deepcopy(subtopic_map).keys())

for element in subtopic_keys: 
    try:
        for dict_object in subtopic_map[element]:
            for key2 in dict_object.keys():
                for index,entry in enumerate(dict_object[key2]['tweets']):
                    count = 0
                    if 'gift' in clean(entry).split():
                        pass
                    if 'gift' not in clean(entry).split():
                        dict_object[key2]['tweets'][index] = 'removed'
    except KeyError:
        pass

这不起作用。注意:唯一的变化是'gift'已被第一个for循环中的element替换,它是一个相同的字符串对象。我通过打印type(element)验证了它,它是字符串类。

subtopic_keys = list(copy.deepcopy(subtopic_map).keys())

for element in subtopic_keys: 
    try:
        for dict_object in subtopic_map[element]:
            for key2 in dict_object.keys():
                for index,entry in enumerate(dict_object[key2]['tweets']):
                    count = 0
                    if element in clean(entry).split():
                        pass
                    if element not in clean(entry).split():
                        dict_object[key2]['tweets'][index] = 'removed'
    except KeyError:
        pass

最后一行代码用“ removed”替换每个条目,这意味着python不能识别任何条目中的字符串,只要它是从dict键派生的。为什么会这样呢? dict键是相同的字符串类对象。

解决方法

我遇到了同样的问题。原来我的列表在所有元素字符串的末尾都有“\n”。 我就是这样解决的。

openList=open("list.txt","r")
list = b.readlines() # this returned \n in each element of the list
list2=[x.replace("\n","") for x in list] #this removes all the \n in all elements in list

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。