在Python中操作字符串

0 投票
5 回答
2740 浏览
提问于 2025-04-16 06:07

如何定义一个函数,这个函数接收一个字符串(句子),并在句号后面插入一个额外的空格,如果句号后面紧跟着一个字母的话。

sent = "This is a test.Start testing!"
def normal(sent):
    list_of_words = sent.split()
    ...

这样应该会打印出

"这是一个测试。开始测试!"

我想我应该用 split() 把字符串分割成一个列表,但接下来该怎么做呢?

附注: 这个解决方案要尽可能简单。

5 个回答

1

没有任何检查的暴力破解:

>>> sent = "This is a test.Start testing!"
>>> k = sent.split('.')
>>> ". ".join(l)
'This is a test. Start testing!'
>>> 

用于去除空格:

>>> sent = "This is a test. Start testing!"
>>> k = sent.split('.')
>>> l = [x.lstrip(' ') for x in k]
>>> ". ".join(l)
'This is a test. Start testing!'
>>> 
8

使用 re.sub。你的正则表达式会匹配一个句号(\.)后面跟着一个字母([a-zA-Z])。你的替换字符串会包含对第二组的引用(\2),也就是在正则表达式中匹配到的那个字母。

>>> import re
>>> re.sub(r'\.([a-zA-Z])', r'. \1', 'This is a test.This is a test. 4.5 balloons.')
'This is a test. This is a test. 4.5 balloons'

注意选择 [a-zA-Z] 作为正则表达式。这只匹配字母。我们不使用 \w,因为那样会把空格也算进去,导致小数点数字出错。

3

这里有一个简单的一行代码,不用正则表达式:

def normal(sent):
    return ".".join(" " + s if i > 0 and s[0].isalpha() else s for i, s in enumerate(sent.split(".")))

下面是一个多行的版本,使用了类似的方法。你可能会觉得这样更容易读懂。

def normal(sent):
    sent = sent.split(".")
    result = sent[:1]
    for item in sent[1:]:
        if item[0].isalpha():
            item = " " + item
        result.append(item)
    return ".".join(result)

不过,使用正则表达式可能是更好的方法。

撰写回答