【问题标题】:How to remove words containing a substring in a python string?如何删除python字符串中包含子字符串的单词?
【发布时间】:2014-05-20 13:16:16
【问题描述】:

当我使用 Twitter API 时,我得到了几个包含链接的字符串(推文),这就是以 'http://' 开头的子字符串。

我怎样才能摆脱这些链接,就是这样,我想删除整个单词

假设我有:

'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre http://t.co/Ad2oWDNd4u'

我想获得:

'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre'

这样的子字符串可能出现在字符串的任何位置

【问题讨论】:

  • 它们会只出现在最后吗?
  • @thefourtheye 我已经习惯看到你了 :P 他们可能不仅仅出现在最后
  • 另外,网址后面会有空格吗?
  • 可能有,@thefourtheye

标签: python


【解决方案1】:

您可以使用re.sub() 将所有链接替换为空字符串:

>>> import re
>>> pattern = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
>>> s = 'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre http://t.co/Ad2oWDNd4u'
>>> pattern.sub('', s)
'Mi grupo favorito de CRIMINALISTICA. Ultima clase de cuatrimestre '

它替换字符串中任何位置的所有链接:

>>> s = "I've used google https://google.com and found a regular expression pattern to find links here https://stackoverflow.com/questions/6883049/regex-to-find-urls-in-string-in-python"
>>> pattern.sub('', s)
"I've used google  and found a regular expression pattern to find links here "                                                                                                                                            

正则表达式取自该线程:

【讨论】:

    【解决方案2】:

    你可以这样做:

    s[:s.index('http://')-1]
    

    如果它并不总是出现在最后,你可以这样做:

    your_list = s.split()
    i = 0
    while i < len(your_list):
        if your_list[i].startswith('http://'):
            del your_list[i]
        else:
            i+=1
    s = ' '.join(your_list)
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 2023-04-03
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2022-11-07
      • 1970-01-01
      相关资源
      最近更新 更多