删除字符串中每个句子中特定符号后的单词

2024-04-26 04:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 这是字符串,例如: “我有一个苹果。我想吃。但是太痛了 我想把它转换成这个: “我有一个苹果要吃它太酸了”

Tags: 字符串苹果太酸太痛
1条回答
网友
1楼 · 发布于 2024-04-26 04:16:58

下面是一种不用regex的方法,使用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.'

相关问题 更多 >