【问题标题】:Removing a string that starts with a substring删除以子字符串开头的字符串
【发布时间】:2019-06-01 20:08:32
【问题描述】:

我想删除所有包含特定子字符串的单词。

Sentence = 'walking my dog https://github.com/'
substring = 'http'

# Remove all words that start with the substring
#...

result = 'walking my dog'

【问题讨论】:

标签: python string substring


【解决方案1】:

这会尊重字符串中的原始间距,而不必过多地摆弄。

import re
string = "a suspect http://string.com   with spaces before and after"
starts = "http"
re.sub(f"\\b{starts}[^ ]*[ ]+", "", string)
'a suspect with spaces before and after'

【讨论】:

    【解决方案2】:

    我们可以使用一种简单的方法。

    1. sentence拆分成单词
    2. 找到所有的作品
    3. 检查该单词是否包含substring 并将其删除
    4. 将剩下的单词重新加入。
    >>> sentence = 'walking my dog https://github.com/'
    >>> substring = 'http'
    >>> f = lambda v, w: ' '.join(filter(lambda x: w not in x, v.split(' ')))
    >>> f(sentence, substring)
    'walking my dog'
    

    解释:

    1. ' '.join(
    2.   filter(
    3.     lambda x: w not in x,
    4.     v.split(' ')   
    6.  )
    7. )
    

    1 星号加入。 2 用于过滤来自4 的所有元素,将字符串拆分为单词。要过滤的条件是substring not in wordnot in 进行了O(len(substring) * len(word)) 的复杂性比较。

    注意:唯一可以加快的步骤是3 行。您将单词与常量字符串进行比较,您可以使用Rabin-Karp String Matching 查找O(len(word)) 中的字符串或Z-Function 查找O(len(word) + len(substring)) 中的字符串

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 2015-02-03
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      相关资源
      最近更新 更多