Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python从文件中删除行_Python - Fatal编程技术网

使用python从文件中删除行

使用python从文件中删除行,python,Python,可能重复: 我需要一些关于如何做到这一点的投入,非常感谢你的投入,我看了其他职位,但没有一个符合我的要求 我需要根据提供的输入字符串匹配文件中的多行注释 例如:- 假设文件“test.txt”有以下注释,如果inputstring=“这是一个测试,脚本编写”需要从文件中删除此注释 import os import sys import re import fnmatch def find_and_remove(haystack, needle): pattern = re.co

可能重复:

我需要一些关于如何做到这一点的投入,非常感谢你的投入,我看了其他职位,但没有一个符合我的要求

我需要根据提供的输入字符串匹配文件中的多行注释

例如:-

假设文件“test.txt”有以下注释,如果inputstring=“这是一个测试,脚本编写”需要从文件中删除此注释

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
回溯(最近一次呼叫最后一次):
文件“comment.py”,第16行,在
查找和删除(f,r“这是一个测试,脚本编写”)
文件“comment.py”,第8行,在find_和_remove中
return-re.sub(模式“,”干草堆)
文件“/usr/lib/python2.6/re.py”,第151行,子文件
返回编译(模式,0).sub(repl,字符串,计数)
TypeError:应为字符串或缓冲区

当我看到这个问题时,首先想到的是“状态机”,每当我想到python中的“状态机”,首先想到的就是“生成器”a.k.a.收益率:

def skip_comments(f):
    """
    Emit all the lines that are not part of a multi-line comment.
    """
    is_comment = False

    for line in f:
        if line.strip().startswith('/*'):
            is_comment = True

        if line.strip().endswith('*/'): 
            is_comment = False
        elif is_comment:
            pass
        else:
            yield line


def print_file(file_name):
    with file(file_name, 'r') as f:
        skipper = skip_comments(f)

        for line in skipper:
            print line,
编辑:user1927396通过指定它只是一个包含特定文本的要排除的特定块来增加赌注。因为它位于注释块内,所以我们不知道是否需要拒绝该块

我的第一个想法是缓冲。阿克。呸。我的第二个想法是一句萦绕在脑海中的话,我已经记了15年了,直到现在都没有用过:“一堆国家机器”


当我看到这个问题时,首先想到的是“状态机”,每当我想到python中的“状态机”,首先想到的就是“生成器”a.k.a.收益率:

def skip_comments(f):
    """
    Emit all the lines that are not part of a multi-line comment.
    """
    is_comment = False

    for line in f:
        if line.strip().startswith('/*'):
            is_comment = True

        if line.strip().endswith('*/'): 
            is_comment = False
        elif is_comment:
            pass
        else:
            yield line


def print_file(file_name):
    with file(file_name, 'r') as f:
        skipper = skip_comments(f)

        for line in skipper:
            print line,
编辑:user1927396通过指定它只是一个包含特定文本的要排除的特定块来增加赌注。因为它位于注释块内,所以我们不知道是否需要拒绝该块

我的第一个想法是缓冲。阿克。呸。我的第二个想法是一句萦绕在脑海中的话,我已经记了15年了,直到现在都没有用过:“一堆国家机器”


这在普林西比应该行得通

def skip(file, lines):
 cline = 0
 result = ""
 for fileLine in file.read():
  if cline not in lines:
   result += fileLine
  cline += 1
 return result

行必须是数字列表,文件必须是打开的文件

这在principe中应该有效

def skip(file, lines):
 cline = 0
 result = ""
 for fileLine in file.read():
  if cline not in lines:
   result += fileLine
  cline += 1
 return result

行必须是一个数字列表,文件必须是一个打开的文件

此文件按照请求执行:删除包含所需字符串的所有多行注释:

将其放入名为
program.txt的文件中

/*
 * This is a test, script written
 * This is a comment line
 * Multi-line comment
 * Last comment
 *
 */

some code

/*
 * This is a comment line
 * And should 
 *     not be removed
 *
 */

more code
然后搜索并替换。只需确保
指针
没有引入一些正则表达式特殊字符

import re

def find_and_remove(haystack, needle):
    pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
    return re.sub(pattern, "", haystack)

# assuming your program is in a file called program.txt
program = open("program.txt", "r").read()

print find_and_remove(program, r"This is a test, script written")
结果是:

some code

/*
 * This is a comment line
 * And should 
 * not be removed
 *
 */

more code
它在

编辑代码中的最后一节:

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)
                # put all the text into f and read and replace...
                f = open(fullname).read()
                result = find_and_remove(f, r"This is a test, script written")

                new_name = fullname + ".new"
                # After testing, then replace newname with fullname in the 
                # next line in order to replace the original file.
                handle = open(new_name, 'w')
                handle.write(result)
                handle.close()

确保在
指针
中转义所有正则表达式特殊字符,例如
()。
如果文本包含括号,例如
(任何文本)
它们应以
(任何文本)的形式出现在
指针

此操作与请求中的操作相同:删除包含所需字符串的所有多行注释:

将其放入名为
program.txt的文件中

/*
 * This is a test, script written
 * This is a comment line
 * Multi-line comment
 * Last comment
 *
 */

some code

/*
 * This is a comment line
 * And should 
 *     not be removed
 *
 */

more code
然后搜索并替换。只需确保
指针
没有引入一些正则表达式特殊字符

import re

def find_and_remove(haystack, needle):
    pattern = re.compile(r'/\*.*?'+ needle + '.*?\*/', re.DOTALL)
    return re.sub(pattern, "", haystack)

# assuming your program is in a file called program.txt
program = open("program.txt", "r").read()

print find_and_remove(program, r"This is a test, script written")
结果是:

some code

/*
 * This is a comment line
 * And should 
 * not be removed
 *
 */

more code
它在

编辑代码中的最后一节:

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)
                # put all the text into f and read and replace...
                f = open(fullname).read()
                result = find_and_remove(f, r"This is a test, script written")

                new_name = fullname + ".new"
                # After testing, then replace newname with fullname in the 
                # next line in order to replace the original file.
                handle = open(new_name, 'w')
                handle.write(result)
                handle.close()


确保在
指针
中转义所有正则表达式特殊字符,例如
()。
如果文本包含括号,例如
(任何文本)
,它们应以
(任何文本)
的形式出现在
指针
中。

停止重新列出此问题。求求你。@Tim-我只是需要一些想法来解决……这有什么不对吗?别再发这个问题了。请。@Tim-我只是需要一些想法来处理..这有什么不对吗?Rob-我只想删除一个特定的多行注释,而不是所有的多行注释Shi Rob-我理解这一部分,但我如何告诉脚本同时执行这两个操作..它需要知道是否.startswith('/*'),并且它包含“这是一个测试,脚本编写的”(删除了我以前的注释;))这有点难,因为你进入了前瞻逻辑。在这种情况下,我要做的不是“通过”这行,而是将所有注释行推到一个列表中。当您到达注释的末尾时,遍历列表。如果你看到目标线,通过。如果你看不到它,请在列表中的每一行都给出它。。。瞧,一切都变得复杂了;)看起来很复杂。如何根据单个输入字符串/行传递列表中的所有行(比如,这是注释行)?请查看编辑。。。但这不是为心虚的人准备的Rob-我只想删除一个特定的多行注释,而不是所有的多行注释Shi Rob-我理解这一部分,但我如何告诉脚本同时执行这两个操作..它需要知道是否.startswith('/*'),它包含“这是一个测试,脚本编写”(删除了我以前的注释;))这有点难,因为你进入了前瞻逻辑。在这种情况下,我要做的不是“通过”这行,而是将所有注释行推到一个列表中。当您到达注释的末尾时,遍历列表。如果你看到目标线,通过。如果你看不到它,请在列表中的每一行都给出它。。。瞧,一切都变得复杂了;)看起来很复杂。如何根据单个输入字符串/行传递列表中的所有行(比如,这是注释行)?请查看编辑。。。但这不适合心脏病患者这可能对我不起作用,因为我的文件不仅包含数字。这是一个常规的c代码你显然不理解代码你可能是对的50%。你能解释一下代码吗?这可能对我不起作用,因为我的文件不仅包含数字。这是一个常规的c代码你显然不理解代码你可能是正确的50%。你能解释一下代码吗?让它在文件上工作有多容易?我对你的代码做了一些更改,使其在目录上循环,并遇到编译错误..我更新了我原来的问题