【问题标题】:str.replace unless string is followed by certain textstr.replace 除非字符串后跟某些文本
【发布时间】:2021-02-07 17:31:25
【问题描述】:

修改之前的问题:

我如何将所有“,”(即逗号后空格)替换为“_”,除非“,”(逗号后空格)后跟单词“LLC”或“Inc”(然后什么都不做)?

我想改变:

  1. “TEXAS ENERGY MUTUAL, LLC、BOBBY GILLIAM、STEVE PEREIRA 和 ANDY STITT”
  2. “Grape, LLC, Andrea Gray, Jack Smith”
  3. “Stephen Winters, Apple, pear, Inc, Sarah Smith”

至此:

  1. “TEXAS ENERGY MUTUAL, LLC_BOBBY GILLIAM_STEVE PEREIRA_ANDY STITT”
  2. “葡萄,LLC_Andrea Gray_Jack Smith”
  3. “Stephen Winters_Apple_pear, Inc_Sarah Smith”

我认为它会从以下代码的一些变体开始,但我无法弄清楚例外条件。

df['Column_Name'] = df['Column_Name'].str.replace(', ','_') 干杯!

【问题讨论】:

  • 您可以搜索 , , LLC, lnc 索引,并只选择不与最后两个选项相交的内容。强烈推荐将索引转换为set
  • ,后面的空格数是否固定为1?或者可以有 0、1 或 2 个或更多空格? , (?!Inc|LLC) 那就不行了,否则,它是一个解决方案(这里可能有一个单词边界,但它取决于实际要求)。
  • 试试replace(r',(?!\s+(?:LLC|Inc)\b)\s+', '_')

标签: python regex pandas dataframe replace


【解决方案1】:

使用 python 正则表达式模块re 与模式, (?!Inc|LLC) 查找所有出现的, 而不遵循IncLLC

import re

strings = ["Banana, orange", "Grape, LLC", "Apple, pear, Inc"]

[re.sub(", (?!Inc|LLC)",'_',string) for string in strings]
#['Banana_orange', 'Grape, LLC', 'Apple_pear, Inc']

【讨论】:

  • 如果 LLC 不在字符串的末尾,它将不起作用。不确定小例子是否必须发生这种情况
【解决方案2】:

您可以将正则表达式替换为negative lookahead

#no idea why Inc|LLC or LLC|Inc will skip the first
df['Column_Name'].str.replace(', (?!=|Inc|LLC)', '_')

输出:

0    TEXAS ENERGY MUTUAL, LLC_BOBBY GILLIAM_STEVE P...
1                    Grape, LLC_Andrea Gray_Jack Smith
2          Stephen Winters_Apple_pear, Inc_Sarah Smith
Name: ColumnName, dtype: object

【讨论】:

  • 这不会添加“_”。
  • @Andrew 是我在此处显示的输出中的情况吗?不知道你的意思。
  • @Andrew 那你为什么还要发布另一个问题?在这里修复它。
  • @Andrew 我没有看到我缺少的东西。当我使用你的新输入时,它会产生你所期望的。我需要你澄清“这不会添加_”
  • 好吧,除非你觉得它有帮助,否则没有必要接受答案......但', (?!=|Inc|LLC)' 是一个使用否定前瞻断言的正则表达式,即:, 后跟任何不是IncLLC(?!=...)negative 前瞻,表示后面跟着不是... 的内容。
【解决方案3】:

简单的方法:

def replace(str):
   x = str.split(', ')
   buf = x[0]
   for i in range(1, len(x)): 
      if x[i].startswith('LLC'):
         buf += ', ' + x[i]
      elif x[i].startswith('Inc'):
         buf += ', ' + x[i]
      else:
         buf += '_' + x[i]
   return buf

然后试试replace('a, b, LLC, d')

【讨论】:

  • 什么意思:"replace('a, b, LLC, d')"
  • 我们定义了一个函数def replace(str);尝试它来测试我们的实现...
猜你喜欢
  • 2017-06-16
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
相关资源
最近更新 更多