有一大堆类似的问题有着相同的解决方案:我如何对照一个较大的字符串检查我的字符串列表,看看是否有匹配的字符串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']
的所有实例,虽然匹配哪一个并不重要,但我需要能够找到它之前还是之后是否存在Cat
或Bear
。匹配字符串的位置并不重要,只是能够确定它之前或之后的内容
在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
{
以下是一些示例输出:
| 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 |
您可以使用以下模式检查
Cat
或Bear
是否出现在感兴趣的单词之前,在本例中是Apple
或Ap.ple
或Ap ple
要创建满足条件的新dataframe列,可以组合
map
和df.str.match
:或使用
numpy.where
:将导致:
使用^{} 从}&
df['data']
列中提取三个新列,即key
、before
&after
,然后在每个{after
列以查找单词前后的所有匹配项:相关问题 更多 >
编程相关推荐