我必须编写一个代码来做两件事:
将多个空格字符压缩为一个。
在句点后添加空格(如果没有句点)。
例如:
input> This is weird.Indeed
output>This is weird. Indeed.
这是我写的代码:
^{pr2}$这段代码接受用户的任何输入并删除所有多余的空格,但它并没有在句点后添加空格(我知道为什么不能,因为拆分函数将句点和下一个单词作为一个单词,我只是不知道如何修复它)
这是我在网上找到的代码:
import re
def correction2(string):
corstr = re.sub('\ +',' ',string)
final = re.sub('\.','. ',corstr)
return final
strn= ("This is as .Indeed")
print (correction2(strn))
这个代码的问题是我不能接受用户的任何输入。它是在程序中预定义的。 那么,有人能建议如何改进这两种代码中的任何一种,以便在用户输入的任何信息上同时实现这两种功能呢?在
这是你想要的吗?在
我已经将regex更改为lookahead模式,请看一下here。在
编辑:按照注释中的要求解释Regex
re.sub()接受(至少)三个参数:Regex搜索模式、匹配模式应替换为的替换以及执行替换的字符串。在
我现在要做的是两个步骤,我使用一个函数的输出作为另一个函数的输入。 首先,内部
re.sub(r' +', ' ', s)
在s
中搜索多个空格(r' +'
),以将它们替换为单个空格。然后外部的re.sub(r'\.(?! )', '. ', ...)
查找不带空格字符的句点,将其替换为'. '
。我使用了一个负lookahead模式来匹配与指定的lookahead模式不匹配的部分(在本例中是普通空格字符)。您可能需要使用此模式play around,这可能有助于更好地理解它。在r
字符串前缀将字符串更改为raw string,其中反斜杠转义被禁用。在这种情况下没有必要,但我习惯于将原始字符串与正则表达式一起使用。在对于更基本的答案,不使用regex:
请尝试以下代码:
相关问题 更多 >
编程相关推荐