可能重复:
Python 3 正则表达式查找多行注释
我需要一些关于如何做到这一点的意见,非常感谢您的意见,我查看了其他帖子,但没有一个符合我的要求。
如何从python中的文件中 删除行使用python从文本文件中删除行
我需要根据提供的输入字符串匹配文件中的多行注释。
例子:-
假设文件“test.txt”有以下注释,如果 inputstring="This is a test, scriptwritten" 这个注释需要从文件中删除
import os
import sys
import re
import fnmatch
def find_and_remove(haystack, needle):
pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
return re.sub(pattern, "", haystack)
for path,dirs,files in os.walk(sys.argv[1]):
for fname in files:
for pat in ['*.cpp','*.c','*.h','*.txt']:
if fnmatch.fnmatch(fname,pat):
fullname = os.path.join(path,fname)
with open(fullname, "r") as f:
find_and_remove(f, r"This is a test, script written")
错误:-
Traceback (most recent call last):
File "comment.py", line 16, in <module>
find_and_remove(f, r"This is a test, script written")
File "comment.py", line 8, in find_and_remove
return re.sub(pattern, "", haystack)
File "/usr/lib/python2.6/re.py", line 151, in sub
return _compile(pattern, 0).sub(repl, string, count)
TypeError: expected string or buffer