首页 > 解决方案 > 删除字符串中每个句子中特定符号后的单词

问题描述

  1. 例如,这是字符串:'我有一个苹果。我想吃它。但它是如此疼痛。我想把它转换成这个:'我有一个苹果想吃,它好痛'

标签: pythonstringindexingdel

解决方案


这是一种无需正则表达式的方法,使用del您提到的方法:

def remove_after_sym(s, sym):
    # Find first word
    first = s.strip().split(' ')[0]

    # Split the string using the symbol
    l = []
    s = s.strip().split(sym)

    # Split words by space in each sentence
    for a in s:
        x = a.strip().split(' ')
        del x[0]
        l.append(x)

    # Join words in each sentence
    for i in range(len(l)):
        l[i] = ' '.join(l[i])

    # Combine sentences
    final = first + ' ' + ' '.join(l)
    final = final.strip() + '.'

    return final

在这里,sym 是一个str(单个字符)。

另外,我在您的示例中非常自由地使用了“句子”一词,sym它是一个点。但是这里的句子真的意味着字符串的一部分被你想要的符号打破。

这是它的输出。

In [1]: remove_after_sym(string, '.')
Out[1]: 'I have an apple want to eat it it is so sore.'

推荐阅读