'''
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')
这只是在文件中写入最后一条多行注释。不是全部
用
替换
\n
。以下是代码:输出:
您可以在中读取整个文件,并在多行模式下应用
re.sub
。 之后(或之前,不要紧……)只需裁剪这三个'
并添加#
:可以使用
re.sub
将一个或多个新行(\n
)替换为单数空格。然后去掉结果(任何尾随空格和前导空格)并将其连接到'#'
:相关问题 更多 >
编程相关推荐