【问题标题】:Split string in words before nth occurrence of hashtags in python在python中第n次出现主题标签之前用单词拆分字符串
【发布时间】:2016-03-03 10:37:28
【问题描述】:

我在 Python 中使用以下代码将字符串拆分为单词:

keywords=re.sub(r'[][)(!,;]', ' ', str(row[0])).split()

想象输入是:

"Hello #world I am in #London and it is #sunny today"

我需要将其拆分为仅在出现第二个标签之前,不需要拆分其余部分,这意味着输出应该是:

['Hello','#world','I','am','in'] 

有没有办法在Python中以这种方式将字符串拆分为关键字?

【问题讨论】:

  • 您的拆分也在结果中的空白处

标签: python regex string


【解决方案1】:

str.find取一个起始位置,所以当你找到第一个使用该索引 + 1 t 时开始寻找第二个然后拆分该子字符串:

s = "Hello #world I am in #London and it is #sunny today"
i =  s.find("#", s.find("#") + 1)
print(s[:i].split())
['Hello', '#world', 'I', 'am', 'in']

你也可以对 index 做同样的事情:

s = "Hello #world I am in #London and it is #sunny today"
i =  s.index("#", s.index("#") + 1)
print(s[:i].split())

如果子字符串不存在,则索引的差异将引发错误。

【讨论】:

    【解决方案2】:

    split 方法接受一个字符作为分割依据,否则它会在空格处分割。

    string_to_split = "Hello #world I am in #London and it is #sunny today"
    # Split on all occurrences of #
    temp = string_to_split.split("#")
    # Join the first two entries with a '#' and remove any trailing whitespace
    temp_two = '#'.join(temp[:2]).strip()
    # split on spaces
    final = temp_two.split(' ')
    

    在终端运行:

    >>> string_to_split = "Hello #world I am in #London and it is #sunny today"
    >>> temp = string_to_split.split("#")
    >>> temp_two = '#'.join(temp[:2]).strip()
    >>> final = temp_two.split(' ')
    >>> final
    ['Hello', '#world', 'I', 'am', 'in']
    

    编辑:将 [2:] 固定为 [:2] 我总是把它们弄混

    编辑:修复了多余的空格问题

    【讨论】:

    • 非常感谢,我认为这个答案更接近我的需要,只是考虑到大量字符串作为输入的时间复杂度,我不确定它是否是最优的?
    【解决方案3】:

    交互式python:

    >>> str="Hello #world I am in #London and it is #sunny today"
    >>> hash_indices=[i for i, element in enumerate(str) if element=='#']
    >>> hash_indices
    [6, 21, 39]
    >>> str[0:hash_indices[1]].split()
    ['Hello', '#world', 'I', 'am', 'in']
    >>> str[hash_indices[1]:]
    '#London and it is #sunny today'
    >>> 
    

    【讨论】:

      【解决方案4】:

      正则表达式和拆分

      source = "Hello #world I am in #London and it is #sunny today"
      reg_out = re.search('[^#]*#[^#]*#', source)
      split_out = reg_out.group().split()
      print split_out[:-1]
      

      O/P:['Hello', '#world', 'I', 'am', 'in']

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-02
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2013-06-08
        • 1970-01-01
        相关资源
        最近更新 更多