【发布时间】:2021-08-22 06:11:17
【问题描述】:
我有一个示例字符串:
"green apple, sly fox, cunning quick fox fur, cool water, yellow sand"
还有一本字典:
strr_dict = {"green": "color", "apple": "fruit", "sly": "behavior", "fox": "animal", "cunning": "behavior", "quick fox": "animal", "cool water": "drink", "yellow": "color", "sand": "matter"}
我想将字符串中的子字符串及其字典中的值显示为数据框。这就是我所做的:
import pandas as pd
sample_str = "green apple, sly fox, cunning quick fox fur, cool water, yellow sand"
strr_dict = {"green": "color", "apple": "fruit", "sly": "behavior", "fox": "animal", "cunning": "behavior", "quick fox": "animal", "cool water": "drink", "yellow": "color", "sand": "matter"}
df_list = []
stripped_list = [i.strip() for i in sample_str.split(',')]
for i in stripped_list:
if i in strr_dict:
df_list.append([i, strr_dict[i]])
else:
for j in i.split():
if j in strr_dict:
df_list.append([j, strr_dict[j]])
else:
df_list.append([j, ""])
strr_df = pd.DataFrame(df_list, columns=['Text', 'Value'])
print(strr_df)
我得到的输出是:
Text Value
0 green color
1 apple fruit
2 sly behavior
3 fox animal
4 cunning behavior
5 quick
6 fox animal
7 fur
8 cool water drink
9 yellow color
10 sand matter
我想要的输出是:
Text Value
0 green color
1 apple fruit
2 sly behavior
3 fox animal
4 cunning behavior
5 quick fox animal
6 fur
7 cool water drink
8 yellow color
9 sand matter
如果子字符串与字典键完全匹配,我想显示这些值。我想知道如何相应地拆分字符串。在这种情况下,cunning quick fox fur 应拆分为cunning、quick fox、fur。但这可能并非总是如此,有时应该将其拆分为cunning、quick fox fur 以从字典中获取它们的值。我对如何处理这种情况感到非常困惑。
【问题讨论】:
-
"green apple, sly fox, cunning quick fox fur, cool water, yellow sand"所以有时每个单词,用空格分隔,是一个键,但有时两个单词一起作为一个键?输入非常混乱 -
@Flying Thunder,没错。有时每个单词都是一把钥匙,有时两个或多个单词加在一起就是一把钥匙。
-
@Animeartist 这是什么逻辑?计算机如何知道两个词什么时候在一起,什么时候不在一起?
-
您必须对照所有字典键检查每个
,分隔的字符串,检查此处是否包含键,然后,当多个键(一个单词和两个单词 - 例如 quick fox 和狐狸)——然后呢?你的例子似乎只想要最长的匹配,所以这听起来是可行的,但是(我知道这是一个 stackoverflow 陈词滥调),听起来更容易确保你的输入格式正确 -
@FlyingThunder,是的,可以像这样检查每个键,但我一直在寻找更有效的解决方案。
标签: python string dataframe dictionary