【问题标题】:Python: Split string such that each substring is a key in a dictionaryPython:拆分字符串,使每个子字符串都是字典中的键
【发布时间】: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 应拆分为cunningquick foxfur。但这可能并非总是如此,有时应该将其拆分为cunningquick 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


【解决方案1】:

所以这确实给出了您指定的输出。我不知道你如何以及为什么想要这个,我不知道这是否适用于你可能拥有的其他输入案例,但它应该 - 随意使用你准备好的任何其他可怕的数据集进行测试。

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(',')]


checklist = []

for i in stripped_list:
    if i in strr_dict:
        df_list.append([i, strr_dict[i]])
        checklist.append(i)
    else:
        for z in list(strr_dict.keys()):
            if z in str(checklist):
                continue
            if z in i:
                try:
                    df_list.append([i, strr_dict[i]])
                    checklist.append(i)
                except:
                    df_list.append([z, strr_dict[z]])
                    checklist.append(z)
    for x in i.split():
        if x not in str(checklist) and x not in list(strr_dict.keys()):
            df_list.append([x, ""])



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 fox    animal
6         fur          
7  cool water     drink
8      yellow     color
9        sand    matter

Process finished with exit code 0

【讨论】:

  • 嗨,非常感谢,它适用于大多数情况。对于像cunning quick fox fur yellow sand 这样的情况,它适用于这个字符串,但最后的yellow sandcool water 之后不会显示。这是我试图做的 NLP 过程的一部分,但我想将这些值显示为数据框。
  • 你是什么意思 - 如果它不起作用,你的输入是什么?当我使用这个输入 "green apple, sly fox, cunning quick fox fur yellow sand, cool water" 它仍然有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多