【问题标题】:splitting text based on word match with python [duplicate]基于单词匹配与python分割文本[重复]
【发布时间】:2020-07-26 19:38:33
【问题描述】:

我有一个字符串,我想根据单词匹配来拆分它。我怎样才能做到这一点? 这是我不完整的尝试

text_ = "Sky is beautiful today" 
test = "beautiful"

if test in text_:
    #Here the logic
    print(text_.split(test))

上述代码不起作用,因为它删除了匹配的单词

预期输出:["Sky is","beautiful", "today"]

【问题讨论】:

  • 是强制只能通过split函数进行拆分,还是我们也可以使用其他方法?
  • 任何有效的东西。这就是我想到的原因
  • 不它没有。答案如下

标签: python regex


【解决方案1】:

正则表达式操作是你的朋友!

更好的方法是使用re.split。这样你只需要 1 行。

请注意,模式(测试)必须是括号内的字符串,以便在输出中包含该单词。

text_ = "Sky is beautiful today" 
test = "(beautiful)"

print(re.split(test, text_))

输出:['Sky is ', 'beautiful', ' today']

【讨论】:

  • 为什么要在字前加()?那不是原来的词
  • () 就是这个词在捕获组中。如果没有 (),单词 beatiful 将不会如您所愿出现在输出中。
  • 我明白了,谢谢你的解释。我改变了我的源代码。我不明白为什么它很重要
  • 这样可以拆分检查两个单词吗?
  • 是的!您可以使用正则表达式或 | 。在这种情况下,我被beautifulmy分开。 test = "(beautiful|my)"
【解决方案2】:

嗯,这是我尝试过的一种方法,虽然很幼稚,但仍然适用于上述情况。

text_ = "Sky is beautiful today" 
test = "beautiful"
s = ""
res = []
if test in text_:
  for word in text_.split(" "):
    if word == test:
      res.append(s)
      res.append(test)
      s = ""
    else:
      s += word + " "
  res.append(s)
print(res)

肯定会有更有效的方法。

输出:-

['Sky is ', 'beautiful', 'today ']

【讨论】:

    【解决方案3】:

    你可以做这样的事情并利用列表切片

    代码

    text = "Sky is beautiful today" 
    element = "beautiful"
    
    #Split string into list elements by the occurrence of a " "
    words = text.split(" ")
    index = words.index(element) #Grab index of specified "word"
    
    preElement = " ".join(words[:index])      #Grab elements before the "word"
    postElement = " ".join(words[index+1:])   #Grab elements after the "word"
    
    #Combination, but only works for first occurrence of the "word"
    output = [preElement,element,postElement]
    print(output)
    

    输出

    ['Sky is', 'beautiful', 'today']
    

    【讨论】:

    • 没问题,但需要进行一些调整才能处理您要查找的单词的多次出现
    猜你喜欢
    • 2011-12-28
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多