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

2024-09-25 00:27:01 发布

您现在位置: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 frequency counter. This is a very important practical

(我想把它算作评论)

我的代码: 进口re

START_PATTERN = "'''\n"
END_PATTERN = "'''\n"

with open('counter.py') as file:
    match = False
    newfile = None
for line in file:
    if re.match(START_PATTERN, line):
        match = True
        newfile = open('my_new_file.txt', 'w')
        continue
    elif re.match(END_PATTERN, line):
        match = False
        newfile.close()
        continue
    elif match:
        newfile.write(line)
        newfile.write('\n')

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


Tags: toreisonmatchlinecounterthis
3条回答

替换\n。以下是代码:

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

输出:

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

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

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  

可以使用re.sub将一个或多个新行(\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'

相关问题 更多 >