【问题标题】:Removing words from a sentence before a keyword from a specific list从特定列表中的关键字之前从句子中删除单词
【发布时间】:2021-02-15 11:43:12
【问题描述】:

我有一个关键字列表keywords = [",", "or", "and"] 还有一句话s = built on the kernel, is written largely in

我想从上面列表中的任何关键字之前删除上面句子中的所有单词,在这种情况下是 "," 。所以输出将是is written largely in.

【问题讨论】:

  • 如果字符串中有多个关键字,如@9​​87654324@,需要什么字符串?

标签: python string nlp


【解决方案1】:
import re

keywords = [",", "or", "and"]
s = "built on the kernel, is written largely in"
split_sentence = re.split(',|or|and',s)[1:]
result = "".join(split_sentence)
print(result)

输出:

is written largely in

【讨论】:

    【解决方案2】:

    您可以将re.split()pattern 一起用作| 连接的keywords 字符串。它将返回由关键字分隔的字符串列表。由于您需要来自list 的最后一个子字符串,因此您可以使用-1 作为索引来访问它。

    例如:

    >>> import re
    >>> keywords = [",", "or", "and"]
    >>> my_str = "Hello, and, or, Stack Overflow"
    
    >>> re.split('|'.join(keywords), my_str)[-1]
    ' Stack Overflow'
    

    此外,如果您想从结果字符串中删除额外的空格,那么您可以在上述字符串上进一步使用str.strip()

    >>> re.split('|'.join(keywords), my_str)[-1].strip()
    'Stack Overflow'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多