在enti中搜索时使用python findall和regex

2024-04-19 02:07:47 发布

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

我在下面的代码中搜索整行中给定的单词。代码来自我之前的question。目前,python搜索行中给定单词的出现情况。但我只想找到完整的单词。你知道吗

当python搜索'jo'时,它不应该返回任何结果,因为没有单词'jo',但是当搜索'jones'时,python应该在第一行返回5

1)我应该如何修改我的搜索?我知道我必须使用正则表达式。但我不知道如何实施。 我试过findall((?i)\bsearch_string\b),但出现了一个错误

2)如果任何列具有数据类型float,下面的代码将给出错误。为了解决这个问题,我将原始的数据帧拆分为非数字列和数字列,在代码下面运行,然后将数字列连接回来。有没有一种优雅的方法可以做到这一点

sales = [{'account': 'jones', 'Jan': '150 jones', 'Feb': '200 jones', 'Mar': '140 jones jones'},
         {'account': '1',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': '1',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]
df = pd.DataFrame(sales)
df

df_list = []

search_string='jones'
for search_string in ['jo', 'jones']:
    #use above method but rename the series instead of setting to
    # a columns. The append to a list.
    df_list.append(df.apply(lambda x: x.str.lower().str.findall(search_string).str.len()).sum(axis=1).astype(int).rename(search_string))

#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df
#

更新的代码使用下面给出的答案

sales = [{'account': 'jones.', 'Jan': '150 jones', 'Feb': '200 .jones', 'Mar': '140 jones jones'},
         {'account': '1',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': '1',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]
df = pd.DataFrame(sales)
df

df_list = []

search_string='jones'
for search_string in ['jones.', 'jone','jones']:
    #use above method but rename the series instead of setting to
    # a columns. The append to a list.
    df_list.append(df.apply(lambda x: x.str.lower().str.findall(r'\b{0}\b'.format(search_string)).str.len()).sum(axis=1).astype(int).rename(search_string))

#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df

Tags: the代码dfsearchstringaccount单词mar
1条回答
网友
1楼 · 发布于 2024-04-19 02:07:47

如果您试图将搜索字符串放入正则表达式中,然后进行匹配,则应该这样做:

import re
test_str = ("account"
                "jones"
                "Jan"
                "150 jones"
                "Feb"
                "200 jones"
                "Mar"
                "140 jones jones")

for search_string in ['jo', 'jones']:
    regex = r'\b{0}\b'.format(search_string)
    number_of_matches = len(re.findall(regex, test_str))

    print(number_of_matches)

还不能和熊猫一起测试,但应该给你足够的工作。你知道吗

相关问题 更多 >