【问题标题】:using str.findall to retrieve the exact match from dictionary使用 str.findall 从字典中检索完全匹配
【发布时间】:2021-08-26 22:15:54
【问题描述】:

我有以下字典

dictionary = {"car":1234, "light-blue":112, "orange":34, "blue":1, "cargo yellow":35}

还有下面的数据框

df_data = {"sentence": ["the summarine is a cargo yellow and orange", "the sky was an amazing light-blue, you should have seen it", "the grass is green", "why you face is purple?", "Light blue as you! HAHA", "Have you ever use the Jungle exploration?"], "extra":['a','b','c','d', 'e', 'f'] }  
df = pd.DataFrame(df_data)

根据我之前提出的问题,我正在使用以下代码:

df['new_col'] = df.sentence.str.extract(pat = f"({'|'.join(dictionary.keys())})")[0]

但是我有两个问题:第一个是如果句子中有多个字典键,则无法提取它;第二个是即使不存在,它也会检索单词 car。为了解决第一个问题,我使用了以下代码:

df.sentence.str.findall(f"|".join(dictionary.keys())).apply(", ".join)

结果如下:

0    car, orange
1     light-blue
2               
3               
4           blue
5     

但是,我仍然有汽车问题,在这种情况下还有蓝色问题。相反,我想要的是这样的:

0  cargo yellow, orange
1            light-blue
2                   nan  
3                   nan   
4                   nan
5                   nan

此外,您对我如何更改代码以获得此结果有任何建议:

0  cargo yellow, orange
1            light-blue
2                   nan  
3                   nan   
4            light blue
5                   nan

编辑:我尝试了以下代码:

for i in dictionary.keys():
    print(i,"\n",df.sentence.str.findall(rf'\b\W?{i}\W?\b'))

在这种情况下,键“汽车”没有被检索到,但考虑到我的字典有 3000 个键/值,它的效率不是很高。

谢谢!

【问题讨论】:

  • 也添加几行示例数据。
  • 对不起,写入的数据没有 ``` 的空格,所以被隐藏了。已添加
  • blue 显然会匹配Light blue,说到car,我在结果字符串中看不到这一点。
  • 使用我提供的代码?我清理内核后尝试再次运行代码,但仍然有汽车结果。
  • 不知何故不在我这边,但这也是意料之中的,因为car包含在cargo

标签: python pandas string dictionary


【解决方案1】:

准备输入数据:

data = {27695: 'I am legit happy because of these news.',
        143703: "Something seems suspicious.I can't recognize that...",
        ...
        48645: 'lol.',
        185265: 'Maybe there is a chance the infinity war sets are next'}

df = pd.DataFrame({"sentence": data.values()}, index=data.keys())

找到完整的单词:

out = df.sentence.str.findall('|'.join([fr'\b{w}\b' for w in dictionary.keys()])) \
                     .apply(lambda l: ','.join(l))

只显示匹配的结果:

>>> out[out != '']
56082      blue,orange
134801            blue
102078            blue
106617            blue
204968            blue
139796    cargo yellow
Name: sentence, dtype: object

【讨论】:

  • 在我提供给你的小数据集中,它可以工作。但是当我尝试在原始版本上运行时,我遇到了这个错误sequence item 0: expected str instance, tuple found
  • 尝试删除.apply(lambda l: ','.join(l)
  • 是的,我已经做到了,结果是这样的[(, , , , , , , , , , , , , , , , , , , )]我在想问题是什么。作为输入,我有一些字符串,所以它应该可以工作
  • @易卜拉欣。您是否解决了输入数据的问题?如果答案对您有帮助,别忘了接受和/或投票?
  • 我没有解决问题,也不知道为什么。你是对的,我会给你接受你的答案,因为你的解决方案在小数据上有效
猜你喜欢
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2019-09-22
  • 2016-08-16
  • 1970-01-01
相关资源
最近更新 更多