gpt4 book ai didi

python - 如何将单元格中的文本与正则表达式匹配并仅保留与正则表达式匹配的文本?

转载 作者:行者123 更新时间:2023-11-30 22:43:24 25 4
gpt4 key购买 nike

我想做的事情:有一个很大的 Excel 工作表,其中有很多随意的客户信息。我想在新的 Excel 文件中以设定的格式对电子邮件地址和其他数据进行排序。

我不太清楚如何将单元格文本(它将具有某种格式,如地址电子邮件压缩在一起等)与正则表达式相匹配,并仅将正则表达式数据保留在列表中。

非常感谢一些帮助。谢谢

import sys, os, openpyxl
def sort_email_from_xl():
sheet = sheet_select() #Opens the worksheet
emailRegex = re.compile(r'''([a-zA-Z0-9._%+-]+@+[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))''',re.VERBOSE)
customeremails = []
for row in range(0, max_row):
if cell.text == emailRegex:
mail = cell.text
customeremails.append(mail)
return customeremails
print(customeremails)

最佳答案

这段代码应该可以工作(尽管我只能测试正则表达式部分):

import sys, os, openpyxl
def sort_email_from_xl():
sheet = sheet_select() #Opens the worksheet
emailRegex = re.compile(".*?([a-zA-Z0-9\._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}).*?")
customeremails = []
for row in range(0, max_row):
if emailRegex.match(cell.text):
mail = emailRegex.match(cell.text).groups()[0]
cell.text = mail
customeremails.append(mail)
print(customeremails)

您的代码存在很多问题。首先关于正则表达式:

  • 正则表达式不允许在您的电子邮件地址周围包含文本,因此在开头和结尾处添加了 .*?
  • 您不需要 re.VERBOSE 部分,因为只有当您想向正则表达式添加内联注释时才需要它,see doc
  • 您允许电子邮件地址之间包含多个 @
  • 您单独匹配了 TLD,这是不必要的

现在,电子邮件正则表达式适用于基本用法,但我绝对建议从 Stackoverflow 上的其他答案中获取经过验证的电子邮件正则表达式。

然后:使用 emailRegex.match(cell.text) 您可以检查 cell.text 是否与您的正则表达式匹配,并使用 emailRegex.match(cell. text).groups()[0] 您仅提取匹配的部分。您的 return 语句也太多了。

For some reason the above code is giving me a NameError: name 'max_row' is not defined

您需要更正行中的循环,例如像documented here

关于python - 如何将单元格中的文本与正则表达式匹配并仅保留与正则表达式匹配的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com