[英]venv cannot find python library even though I definitely have it installed
[英]Python: will not find a string in a list even though it definitely is there
這應該是一個如此簡單的問題,但它讓我發瘋。 當我在字符串列表中搜索關鍵字'gift'時,只要我手動設置字符串'gift',python就會找到它。 當我從字典鍵派生字符串時,即使字典鍵是沒有拼寫錯誤的相同字符串對象,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 循環中的元素替換,這是一個相同的字符串對象。 我通過打印 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.