用一个空格替换单个换行和单个换行的pythoninc方法是什么?

时间:2018-08-07 04:53:19

标签: python python-3.x nlp

我有一个字符串:

"2\nOur\nstrategy drives \nsustainably higher profits and margins\n\nStrengthening our hubs is a critical foundation to maximize profitability\n\nDriving revenue improvements from all areas of business\n\nImproving efficiency and productivity \n\nGreater accountability and transparency\n"

输出应为:

"2 Our strategy drives sustainably higher profits and margins\nStrengthening our hubs is a critical foundation to maximize profitability\nDriving revenue improvements from all areas of business\nImproving efficiency and productivity \nGreater accountability and transparency "

3 个答案:

答案 0 :(得分:3)

Pythonic解决方案:

'\n'.join(e.replace('\n', ' ') for e in s.split('\n\n'))

首先,分割出现'\n\n'的字符串,然后在列表的每个元素中用'\n'替换' ',最后,将所有内容与{{1 }}。

另一种解决方案

我将使用一个临时助手字符串,该字符串允许我临时替换双换行,然后用空格替换单个换行符,然后用换行符替换临时助手字符串:

假设您的字符串为'\n'

s

答案 1 :(得分:3)

创建映射字典:

dct = {'\n\n': '\n', '\n': ' '}

使用 re.sub (此正则表达式的顺序很重要):

re.sub(r'(\n\n|\n)', lambda x: dct[x.group()], s)

输出:

'2 Our strategy drives  sustainably higher profits and margins\nStrengthening our hubs is a critical foundation to maximize profitability\nDriving revenue improvements from all areas of business\nImproving efficiency and productivity \nGreater accountability and transparency '

对此有一些解释。 Python的正则表达式模块不支持重叠匹配,因此当它匹配\n\n时,它也将不匹配\n,这使您可以在一个步骤中完成两个替换。

答案 2 :(得分:0)

使用re.sub

import re
s = "string\n\n\nwith\n\nmultiple\n\n\nnewlines"
# Replace all multiple newlines with one newline
new_string = re.sub(r'\n+', '\n', s)