在python字符串的句点后添加空格时遇到问题

2024-10-01 09:18:50 发布

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

我必须编写一个代码来做两件事:

  1. 将多个空格字符压缩为一个。

  2. 在句点后添加空格(如果没有句点)。

例如:

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))

这个代码的问题是我不能接受用户的任何输入。它是在程序中预定义的。 那么,有人能建议如何改进这两种代码中的任何一种,以便在用户输入的任何信息上同时实现这两种功能呢?在


Tags: 代码用户restringisthis单词final
3条回答

这是你想要的吗?在

import re

def corr(s):
    return re.sub(r'\.(?! )', '. ', re.sub(r' +', ' ', s))

s = input("> ")
print(corr(s))

我已经将regex更改为lookahead模式,请看一下here。在


编辑:按照注释中的要求解释Regex

re.sub()接受(至少)三个参数:Regex搜索模式、匹配模式应替换为的替换以及执行替换的字符串。在

我现在要做的是两个步骤,我使用一个函数的输出作为另一个函数的输入。 首先,内部re.sub(r' +', ' ', s)s中搜索多个空格(r' +'),以将它们替换为单个空格。然后外部的re.sub(r'\.(?! )', '. ', ...)查找不带空格字符的句点,将其替换为'. '。我使用了一个负lookahead模式来匹配与指定的lookahead模式不匹配的部分(在本例中是普通空格字符)。您可能需要使用此模式play around,这可能有助于更好地理解它。在

r字符串前缀将字符串更改为raw string,其中反斜杠转义被禁用。在这种情况下没有必要,但我习惯于将原始字符串与正则表达式一起使用。在

对于更基本的答案,不使用regex:

>>> def remove_doublespace(string):
...     if '  ' not in string:
...         return string
...     return remove_doublespace(string.replace('  ',' '))
...
>>> remove_doublespace('hi there  how    are   you.i am fine. '.replace('.', '. '))
'hi there how are you. i am fine. '

请尝试以下代码:

>>> s = 'This is weird.Indeed'
>>> def correction(s):
    res = re.sub('\s+$', '', re.sub('\s+', ' ', re.sub('\.', '. ', s)))
    if res[-1] != '.':
       res += '.'
    return res

>>> print correction(s)
This is weird. Indeed.

>>> s=raw_input()
hee   ss.dk
>>> s
'hee   ss.dk'
>>> correction(s)
'hee ss. dk.'

相关问题 更多 >