Python 合并三个单引号之间的行,然后将起始引号替换为'#';

Python 合并三个单引号之间的行,然后将起始引号替换为'#';,python,Python,所需输出: ''' Created on Mar 11, 2017 @author: XXZ This file is to demonstrate the word frequency counter. This is a very important practical ''' (我想把它算作评论) 我的代码: 进口稀土 #Created on Mar 11, 2017 @author: XXZ This file is to demonstrate the word frequen

所需输出:

'''
Created on Mar 11, 2017

@author: XXZ
This file is to demonstrate the word frequency counter. This is a very 
important practical

'''
(我想把它算作评论)

我的代码: 进口稀土

#Created on Mar 11, 2017 @author: XXZ This file is to demonstrate the word frequency counter. This is a very important practical

这只是在文件中写入最后一条多行注释。并非全部。

您可以使用
re.sub
将一行或多行新行(
\n
)替换为单个空格。然后去掉结果(任何尾随空格和前导空格),并将其连接到一个
“#”


\n
替换为
。下面是一个代码:

import re
'#' + re.sub('\n+',' ',s).strip()
#'#Created on Mar 11, 2017 @author: XXZ This file is to demonstrate the word frequency counter. This is a very  important practical'
输出:

a = '''
Created on Mar 11, 2017

@author: XXZ
This file is to demonstrate the word frequency counter. This is a very 
important practical

'''

print("#"+a.replace("\n"," "))

使用
str.join

Ex:

# Created on Mar 11, 2017  @author: XXZ This file is to demonstrate the word frequency counter. This is a very  important practical  
s = '''
Created on Mar 11, 2017

@author: XXZ
This file is to demonstrate the word frequency counter. This is a very 
important practical

'''
print("# "+ " ".join(i.strip() for i in s.split()) )
输出:

# Created on Mar 11, 2017  @author: XXZ This file is to demonstrate the word frequency counter. This is a very  important practical  
s = '''
Created on Mar 11, 2017

@author: XXZ
This file is to demonstrate the word frequency counter. This is a very 
important practical

'''
print("# "+ " ".join(i.strip() for i in s.split()) )

您可以在中读取整个文件,并在多行模式下应用
re.sub
。 之后(或之前,不要紧…)只需裁剪这三个
并添加


你试过什么,你坚持什么?为什么输出在字频计数器前会出现分裂?它没有分裂,应该在同一行。你为什么要这样做?与docstring不同,注释不可用于
帮助
等。它们不仅仅是注释。它们是文档字符串。也许给问题添加一些真实的上下文会有帮助?正确,即使我将
'\n'
替换为
'\s'
,这样两行就不会靠得太近……它不会将两行连在一行中。@nehaj现在看到答案了;这和你想要的不完全一样吗?它把“#”放在每行的前面。但不会将行连接成一行。不,不会,它会删除所有行,因此根据定义,结果只有一行。谢谢它工作了。你能解释一下“flags=re.MULTILINE”通常是逐行工作的,所以你不能匹配换行符。此模式使
re
将整个文本作为一个块处理。另见
import re
with open('test.py', 'r') as f:
    txt = f.read()
    print('IN:\n', txt)
    txt = re.sub('\n', ' ', txt, flags=re.MULTILINE)
    txt = '#' + txt[3:-3]
    print('\nOUT:\n',txt)


IN:
 '''
Created on Mar 11, 2017

@author: XXZ
This file is to demonstrate the word frequency counter. This is a very 
important practical

'''

OUT:
 # Created on Mar 11, 2017  @author: XXZ This file is to demonstrate the word frequency counter. This is a very  important practical