【问题标题】:pythonic way to identify and remove sub strings from stringspythonic从字符串中识别和删除子字符串的方法
【发布时间】:2020-12-04 12:25:43
【问题描述】:

我有一个大的 numpy 字符串数组,其中数组的一些元素是好的字符串,有些元素有特殊字符(通常在字符串的开头,有些在里面有各种引号中的子字符串)。我想识别字符串中包含字符串的元素,将字符串存储在其中并将其从原始字符串中删除。

示例:


my_array = ['# this is the "Sharpest" hashtag ever', 'life as we know it', '" what would you do?', 'this was an "arbitrary" result',  'what do you mean']

corrected_array = ['# this is the hashtag ever', 'life as we know it', '" what would you do?',
                   'this was an result', 'what do you mean']

如您所见,“Sharpest”和“arbitrary”这两个词已从更正后的数组中删除。 有没有办法可以识别子字符串并有效地将它们从原始字符串中删除

【问题讨论】:

  • my_array 中的部分字符串无效,导致语法错误。在构建该列表时,您将不得不解决这个问题。显示如何创建 my_array 的代码。
  • 所以你想删除包含在引号之间的每个字符串?正如@GAEfan 所说,'# this is the 'Sharpest' hashtag ever' 是无效字符串,因此您可能必须更改字符串或子字符串的封装引号
  • 我刚刚注意到,字符串在每个元素中都是有效的,这是我提出问题时的语法错误,但最初的整体问题仍然存在
  • 这能回答你的问题吗? How to delete the words between two delimiters?

标签: python regex pandas string numpy


【解决方案1】:

您可以使用re.sub

import re

[re.sub('["\']([^"]*)["\']', "", s) for s in my_array]
['# this is the  hashtag ever', 'life as we know it', '" what would you do?', 't
his was an  result', 'what do you mean']

【讨论】:

    【解决方案2】:

    试试这个

    import re
    corrected_array = [re.sub('"[^"]*"', '', s.replace("'", '"')) for  s in my_array]
    

    【讨论】:

      【解决方案3】:

      您可以尝试一种蛮力方法来识别与第一个 " 和最后一个引号相关联的索引,然后排除列表中找到第一个和最后一个引号的所有元素

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2017-12-17
        • 2018-03-14
        • 1970-01-01
        • 2014-05-13
        • 2019-09-08
        • 1970-01-01
        相关资源
        最近更新 更多