每日一题23:统计文本中单词出现的次数

一、每日一题

解答:

python 复制代码
import pandas as pd
def count_occurrences(files: pd.DataFrame) -> pd.DataFrame:
    bull_cnt = len(files[files['content'].str.contains(r'\sbull\s')])
    bear_cnt = len(files[files['content'].str.contains(r'\sbear\s')])
    res_df = pd.DataFrame(
        {
            'word': ['bull', 'bear'],
            'count': [bull_cnt, bear_cnt]
        }
    )
    return res_df

题源:Leetcode

二、 总结

files['content'].str.contains(r'\sbull\s'):

  • 使用 str.contains() 方法来查找 content 列中包含匹配正则表达式 r'\sbull\s' 的行。
  • 正则表达式**r'\sbull\s'** 寻找以空白字符(空格)开头和结尾的 "bull" 字符串:
    • \s 表示空白字符(比如空格、制表符等)。
    • 因此,r'\sbull\s' 匹配的是整个单词 "bull",而不会匹配诸如 "bulldog" 或 "bullish" 这样的部分匹配。

2024.5.26

相关推荐
爬山算法2 小时前
Redis(158)Redis的主从同步问题如何解决?
数据库·redis·缓存
小马爱打代码4 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
小坏讲微服务4 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z894 小时前
springboot 异步操作
java·spring boot·mybatis
i***13244 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白4 小时前
后端:SpringMVC
java
IT_Octopus4 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88994 小时前
Spring详解
java·后端·spring
S***26754 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
2501_941148155 小时前
多语言微服务架构与边缘计算技术实践:Python、Java、C++、Go深度解析
数据库