【问题标题】:Regex Pattern in Python for special charatersPython中用于特殊字符的正则表达式模式
【发布时间】:2022-01-09 00:43:48
【问题描述】:

几天前我在这里问了一个类似的问题,这对我很有帮助!我想要构建的一个新挑战是进一步开发正则表达式模式以在此迭代中查找特定格式,我认为我已经使用正则表达式 101 来构建/测试正则表达式代码解决了这个问题,但是在 Python 中应用时收到“模式不包含组” '。下面是一个测试 df,以及结果应该是什么样的/通过 StackOverflow 提供的代码的图像,该代码仅适用于数字。

       
df = pd.DataFrame([["{1} | | Had a Greeter welcome clients {1.0}     | | Take measures to ensure a safe and organized distribution {1.000}         | | Protected confidentiality of clients (on social media, pictures, in conversation, own congregation members receiving assistance, etc.)",
                    "{1.00}  | | Chairs for clients to sit in while waiting {1.0000}     | | Take measures to ensure a safe and organized distribution"],
                   ["{1  } | Financial literacy/budgeting {1   } | | Monetary/Bill Support {1}    | | Mental Health Services/Counseling",
                    "{1}| | Clothing Assistance {1       }  | | Healthcare {1}    | | Mental Health Services/Counseling {1}     | | Spiritual Support {1}      | | Job Skills Training"]
                    ] , columns = ['CF1', 'CF2'])

这是仅适用于数字的迭代代码。我用我的新正则表达式模式更改了模式搜索,但它不起作用。

原码:(df.stack().str.extractall('(\d+)')[0] .groupby(level=[0,1]).sum().unstack())

新代码(无法识别模式):(df.stack().str.extractall(r'(?<=\{)[\d+\.\ ]+(?=\})')[0].astype(int) .groupby(level=[0,1]).sum().unstack())

**在测试 df 中,您将看到我只想捕获“{}”之间的数字,并且在我想要捕获和求和的数字后面有小数和空格的混合。新模式在应用程序中不起作用,所以任何帮助都会很棒! **

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    你可以使用'\{([\d.]+)\}':

    (df.stack().str.extractall(r'\{([\d.]+)\}')[0]
       .astype(float).groupby(level=[0,1]).sum().unstack())
    

    输出:

       CF1  CF2
    0  3.0  2.0
    1  1.0  4.0
    
    仅作为 int:
    (df.stack().str.extractall(r'\{(\d+)(?:\.\d+)?\}')[0]
       .astype(int).groupby(level=[0,1]).sum().unstack())
    

    输出:

       CF1  CF2
    0    3    2
    1    1    4
    

    【讨论】:

    • 再次感谢@Mozay!您能否解释一下为什么格式与 Regex 101 中的格式不同?也可以包含空格,因为某些“{1}”将空格作为不同类型的格式
    • 可以,可以加\s* -> '\{(\d+)(?:\.\d+)?\s*\}'
    【解决方案2】:

    您的(?<=\{)[\d+\.\ ]+(?=\}) 正则表达式不包含捕获组,而Series.str.extractall 至少需要一个捕获组才能输出值。

    你需要使用

    (df.stack().str.extractall(r'\{\s*(\d+(?:\.\d+)?)\s*}')[0].astype(float) .groupby(level=[0,1]).sum().unstack())
    

    输出:

       CF1  CF2
    0  3.0  2.0
    1  3.0  5.0
    

    \{\s*(\d+(?:\.\d+)?)\s*} 正则表达式匹配

    • \{ - 一个 { 字符
    • \s* - 零个或多个空格
    • (\d+(?:\.\d+)?) - 第 1 组(请注意,此组捕获的值将是 extractall 方法的输出,它需要至少一个捕获组):一个或多个数字,然后可选出现 . 和一个或更多数字
    • \s* - 零个或多个空格
    • } - 一个 } 字符。

    请参阅regex demo

    【讨论】:

    • 谢谢@Wiktor!这完美!我将不得不调查为什么我的原始正则表达式代码在应用程序中不起作用
    • @BeginnerProgrammer 请参阅我的答案的顶部。此外,(?<=\{)[\d+\.\ ]+(?=\}) 只匹配一个或多个+.、紧接在{ 之后和紧接在} 之前的空格或数字。因此,它甚至可以在{...} 中“捕获”...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多