使用any()从字符串列表中标识匹配的字符串?

2024-05-31 23:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

有一大堆类似的问题有着相同的解决方案:我如何对照一个较大的字符串检查我的字符串列表,看看是否有匹配的字符串How to check if a string contains an element from a list in PythonHow to check if a line has one of the strings in a list?

我有一个不同的问题:如何对照一个较大的字符串检查我的字符串列表,查看是否有匹配项,并隔离该字符串,以便可以相对于匹配的字符串执行另一个字符串操作

以下是一些示例数据:

| id     | data                |
|--------|---------------------|
| 123131 | Bear Cat Apple Dog  |
| 123131 | Cat Ap.ple Mouse    |
| 231321 | Ap ple Bear         |
| 231321 | Mouse Ap ple Dog    |

最后,我试图找到“apple”['Apple', 'Ap.ple', 'Ap ple']的所有实例,虽然匹配哪一个并不重要,但我需要能够找到它之前还是之后是否存在CatBear。匹配字符串的位置并不重要,只是能够确定它之前或之后的内容

Bear Cat Apple Dog中,熊在苹果之前,尽管猫挡着路

下面是我的示例代码:

data = [[123131, "Bear Cat Apple Dog"], ['123131', "Cat Ap.ple Mouse"], ['231321', "Ap ple Bear"], ['231321', "Mouse Ap ple Dog"]] 
df = pd.DataFrame(data, columns = ['id', 'data'])

def matching_function(m): 
     matching_strings = ['Apple', 'Ap.ple', 'Ap ple']

     if any(x in m for x in matching_strings):
          # do something to print the matched string
          return True

df["matched"] = df['data'].apply(matching_function)

在正则表达式中这样做会更好吗

现在,函数只返回true。但是如果有匹配项,我想它也可以返回matched_bear_before{},或者对Cat返回相同的值,并将其填充到df['matched']列中

以下是一些示例输出:

| id     | data                | matched |
|--------|---------------------|---------|
| 123131 | Bear Cat Apple Dog  | TRUE    |
| 123131 | Cat Ap.ple Mouse    | TRUE    |
| 231321 | Ap ple Bear         | TRUE    |
| 231321 | Mouse Ap ple Dog    | FALSE   |

Tags: to字符串inappledfdataifcat
2条回答

您可以使用以下模式检查CatBear是否出现在感兴趣的单词之前,在本例中是AppleAp.pleAp ple

^(?:Cat|Bear).*Ap[. ]*ple|Ap[. ]*ple.*(?:Cat|Bear)

要创建满足条件的新dataframe列,可以组合mapdf.str.match

>>> df['matched'] = list(map(lambda m: "True" if m else "False", df['data'].str.match('^(?:Cat|Bear).*Ap[. ]*ple|Ap[. ]*ple.*(?:Cat|Bear)')))

或使用numpy.where

>>> df['matched'] = numpy.where(df['data'].str.match('^(?:Cat|Bear).*Ap[. ]*ple|Ap[. ]*ple.*(?:Cat|Bear)'),'True','False')

将导致:

>>> df
       id                data matched
0  123131  Bear Cat Apple Dog    True
1  123131    Cat Ap.ple Mouse    True
2  231321         Ap ple Bear    True
3  231321    Mouse Ap ple Dog   False

使用^{}df['data']列中提取三个新列,即keybefore&after,然后在每个{}&after列以查找单词前后的所有匹配项:

import re

keys = ['Apple', 'Ap.ple', 'Ap ple']
markers = ['Cat', 'Bear']

p =  r'(?P<before>.*?)' + r'(?P<key>' +'|'.join(rf'\b{re.escape(k)}\b' for k in keys) + r')' + r'(?P<after>.*)'
m = '|'.join(markers)

df[['before', 'key', 'after']] = df['data'].str.extract(p)
df['before'] = df['before'].str.findall(m)
df['after'] = df['after'].str.findall(m)

df['matched'] = df['before'].str.len().gt(0) | df['after'].str.len().gt(0)

# print(df)

       id                data       before     key   after  matched
0  123131  Bear Cat Apple Dog  [Bear, Cat]   Apple      []     True
1  123131    Cat Ap.ple Mouse        [Cat]  Ap.ple      []     True
2  231321         Ap ple Bear           []  Ap ple  [Bear]     True
3  231321    Mouse Ap ple Dog           []  Ap ple      []    False

相关问题 更多 >