跳至主要内容

使用正则表达式清洗字符串

本教程选取自 DataCamp 的《Cleaning Data in Python》课程内容,带您使用正则表达式清洗字符串。
· 4分钟 阅读

使用 AI 探索

如果您想参加我们的免费 R 入门课程,请点击此链接。

从字符串中提取数值

从字符串中提取数字是一项常见任务,尤其是在处理非结构化数据或日志文件时。

假设您有如下字符串:'the recipe calls for 6 strawberries and 2 bananas'。

提取出其中的 6 和 2 会很有用,例如后续用来比较草莓与香蕉的比例。

当使用正则表达式提取多个数字(更准确地说,是多个模式匹配)时,您可以使用 re.findall() 函数。Dan 在视频中没有讨论这一点,但用法很直接:将模式与字符串传给 re.findall(),它会返回所有匹配项组成的列表。

操作指南

  • 导入 re。
  • 编写一个模式,在以下字符串中找到所有数字:'the recipe calls for 10 strawberries and 1 banana'。为此:
    • 使用 re.findall() 函数,并传入两个参数:模式,其次是字符串。
    • \d 是匹配数字所需的模式。其后应加上 +,表示前一个元素匹配一次或多次。这样可以确保将 10 视为一个数字,而不是 1 和 0。
  • 打印匹配结果,确认您的正则表达式找到了 10 和 1。

         # Import the regular expression module
         ____

         # Find the numeric values: matches
         matches = re.findall('____', '____')

         # Print the matches
         print(____)

         

如果理解了,请继续下一道练习!如果还不太清楚,请观看下面的概览视频。

在 Python 中使用正则表达式清洗字符串的概览视频

模式匹配

在本练习中,您将继续练习正则表达式技能。针对提供的每个字符串,您的任务是编写相应的匹配模式。

操作指南

  • 编写用于匹配以下内容的模式:
    • 格式为 xxx-xxx-xxxx 的电话号码。您已在前一练习中完成过。
    • 格式为:一个美元符号,任意位数的数字,一个小数点,2 位数字的字符串。
      • 使用 \$ 匹配美元符号,\d* 匹配任意位数的数字,\. 匹配小数点,\d{x} 匹配 x 位数字。
  • 一个大写字母,后接任意数量的字母数字字符。
    • 使用 [A-Z] 匹配任意大写字母,后接 \w* 匹配任意数量的字母数字字符。

          # Write the first pattern
          pattern1 = bool(re.match(pattern='____', string='123-456-7890'))
          print(pattern1)

          # Write the second pattern
          pattern2 = bool(re.match(pattern='____', string='$123.45'))
          print(pattern2)

          # Write the third pattern
          pattern3 = bool(re.match(pattern='____', string='Australia'))
          print(pattern3)
          

如果您想进一步学习本课程,这里有链接。

查看 DataCamp 的Python 字符串教程。

主题