python - How to search a partial text in dict?
问题描述
I have a dictionary and would like to be able to search with a partial variable and return a text.
df = pd.read_csv('MY_PATH')
d = defaultdict(lambda: 'Error, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())
d[last_msg()]
last_msg()
should be my partial variable, and d
is my dictionary.
The index on my dictionary is column msg
from df
.
In column msg
i have a sample like Jeff Bezos
.
In column reply
i have a matching reply Jeff Bezos is the CEO of Amazon
How can I search a partial value in column msg
and return matching value from column reply
?
I want to search just Jeff
or just Bezos
and get the matching reply Jeff Bezos is the CEO of Amazon
PS. Alternatives to defaultdict
may also help improve the code.
EDIT: last_msg()
code extracts a text from selenium element.
def last_msg():
try:
post = driver.find_elements_by_class_name("_12pGw")
ultimo = len(post) - 1
texto = post[ultimo].find_element_by_css_selector(
"span.selectable-text").text
return texto
except Exception as e:
print("Error, input not valid")
When I print(d):
defaultdict(<function <lambda> at 0x0000021F959D37B8>, {'Jeff Bezos': 'Jeff Bezos is the CEO of Amazon', 'Serguey Brin': 'Serguey Brin co-founded Google', nan: nan})
When I print(df)
Unnamed: 0 msg reply
0 0 Jeff Bezos Jeff Bezos is the CEO of Amazon
1 1 Serguey Brin Serguey Brin co-founded Google
2 2 NaN NaN
3 3 NaN NaN
解决方案
我找到了一种方法来解决我自己的问题:
d = df.set_index('msg')['reply'].to_dict()
...
try:
x = next(v for k, v in d.items() if last_msg() in k)
except StopIteration:
x = 'Error, input not listed'
推荐阅读
- java - 如何从json中删除元素,同时使用java从xml解析
- mysql - 从日期组中获取 MIN 和 MAX 值
- c++ - 如何计算具有指定类型的表达式的相对和绝对精度
- javascript - 反应中的外部Js对象
- css - 无法使用触摸屏滚动 Vaadin 对话框
- mysql - AWS - Laravel 应用程序的 EC2 和 RDS MultiAZ 性能
- python - 如何解决问题以重塑从 Python 中的 x_train 派生的图像中的过程?
- android-studio - LogCat 在 Android Studio 中不在 Android Studio 项目中
- php - 带有或条件的 PHP 大小写切换
- c# - RestSharp 请求返回状态码 0