python取消注释右行

发布于 2024-09-28 04:33:42 字数 588 浏览 3 评论 0原文

我有一个文件如下:

line 1: _____
   ...
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
#export CONFIG = CCC_defconfig
   ...
other lines

我想操作该文件,以便根据给定的字符串,我可以导出正确的“CONFIG”,并评论其他文件。 例如,如果我得到“CcC”,那么该文件将被操纵,

line 1: _____
    ...
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
export CONFIG = CCC_defconfig
    ...
other lines

在 python 中执行此操作的好方法是什么?

提前致谢!!

I have a file as follows:

line 1: _____
   ...
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
#export CONFIG = CCC_defconfig
   ...
other lines

I want manipulate the file, so that based on the given string, I could export the right "CONFIG", and comment the others.
e.g. if I got "CcC", then the file would be manipulated as

line 1: _____
    ...
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
export CONFIG = CCC_defconfig
    ...
other lines

what the good way to do it in python?

Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

巡山小妖精 2024-10-05 04:33:42

那么为什么不将其设置为

line = 'xxxx'
CONFIG = default_deconfig

if line == 'AAA':
    CONFIG =  AAA_defconfig
elif line == 'CCC':
    CONFIG =  CCC_defconfig
...

除非这不是一个 python 文件并且您想要操作它。看起来是这样的。

在这种情况下,创建一个配置生成器,它将根据行变量创建一个配置文件。

[编辑:基于评论]

您可能需要进行一些调整,但这应该有效。

# Simple , crude solution

f = open('file1', 'r')
manipulated_lines = []
readFirstLine = False
config = ''
configComma = ''
uncommentLine = 0
for line in f:
    tokens = line.split()

    if uncommentLine == 1:
        # this is comment line
        if tokens[0] == '#export':
            manipulated_lines.append(line[1:])
            uncommentLine = uncommentLine + 1
            continue
    elif uncommentLine > 1:
        manipulated_lines.append(line)
        continue

    if not readFirstLine: 
        config = line.rstrip('\n')
        configComma = config + ','
        readFirstLine = True

    # Process additional lines 
    manipulated_lines.append(line)

    if len(tokens) > 0 and tokens[0] == '#':
        if tokens[1] == 'for':
            if config in tokens or configComma in tokens:
                uncommentLine = uncommentLine + 1
                continue

print manipulated_lines
f.close()
fw = open('file2', 'w')
fw.writelines(manipulated_lines)
fw.close()

输入:文件1

CCC
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
#export CONFIG = CCC_defconfig
   ...

输出:文件2

CCC
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
export CONFIG = CCC_defconfig
   ...

Then why not make it as

line = 'xxxx'
CONFIG = default_deconfig

if line == 'AAA':
    CONFIG =  AAA_defconfig
elif line == 'CCC':
    CONFIG =  CCC_defconfig
...

unless this is not a python file and you want to manipulate it. It looks like that.

In that case create a config generator which will create a config file based on the line variable.

[Edit: Based on comments]

You might have to make some adjustments but this should work.

# Simple , crude solution

f = open('file1', 'r')
manipulated_lines = []
readFirstLine = False
config = ''
configComma = ''
uncommentLine = 0
for line in f:
    tokens = line.split()

    if uncommentLine == 1:
        # this is comment line
        if tokens[0] == '#export':
            manipulated_lines.append(line[1:])
            uncommentLine = uncommentLine + 1
            continue
    elif uncommentLine > 1:
        manipulated_lines.append(line)
        continue

    if not readFirstLine: 
        config = line.rstrip('\n')
        configComma = config + ','
        readFirstLine = True

    # Process additional lines 
    manipulated_lines.append(line)

    if len(tokens) > 0 and tokens[0] == '#':
        if tokens[1] == 'for':
            if config in tokens or configComma in tokens:
                uncommentLine = uncommentLine + 1
                continue

print manipulated_lines
f.close()
fw = open('file2', 'w')
fw.writelines(manipulated_lines)
fw.close()

Input: file1

CCC
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
#export CONFIG = CCC_defconfig
   ...

Output: file2

CCC
# for AAA
#export CONFIG = AAA_defconfig

# for BBB, BbB, Bbb, BBb3
#export CONFIG = BBB_defconfig

# for CCC, CcC, Ccc, Ccc1
export CONFIG = CCC_defconfig
   ...
冰雪梦之恋 2024-10-05 04:33:42
def select_export(text, source, destination):
    uncomment_next = False
    for line in source:
        line = line.strip()
        if line.startswith('# for ') and text in set(t.strip() 
                for t in line[6:].split(',')):
            uncomment_next = True
        elif line.startswith('#') and uncomment_next:
            line = line[1:]
            uncomment_next = False
    destination.write(line + '\n')



with open('source') as f:
    with open('destination', 'w') as w:
        select_export('CcC', f, w)
def select_export(text, source, destination):
    uncomment_next = False
    for line in source:
        line = line.strip()
        if line.startswith('# for ') and text in set(t.strip() 
                for t in line[6:].split(',')):
            uncomment_next = True
        elif line.startswith('#') and uncomment_next:
            line = line[1:]
            uncomment_next = False
    destination.write(line + '\n')



with open('source') as f:
    with open('destination', 'w') as w:
        select_export('CcC', f, w)
天冷不及心凉 2024-10-05 04:33:42

IMO 更干净、更易读的方法。

(是的,要修改文件中的一行,您必须覆盖并重写整个文件。)

#!/usr/bin/env python2.7
import re

def find_and_modify(config_file, given_string):

    with open(config_file) as f:
        lines = f.readlines()

    given_string_re = re.compile(r'# for .*{}'.format(given_string))

    # line #'s that start with either "export" or "#export"
    export_line_numbers = []
    # the line # containing the given_string we're searching for
    uncomment_line_number = None

    for i,line in enumerate(lines):
        if re.match(r'#?export', line):
            export_line_numbers.append(i)
            prev_line = lines[i-1]
            if given_string_re.match(prev_line):
                uncomment_line_number = i

    for i in export_line_numbers:
        if i == uncomment_line_number:
            lines[i] = re.sub(r'^#*', '', lines[i])
        else:
            lines[i] = re.sub(r'^#*', '#', lines[i])

    with open(config_file, 'w') as f:
        f.writelines(lines)

find_and_modify('some_file', 'AAA')
find_and_modify('some_file', 'CcC')

A little cleaner more readable approach IMO.

(And, yes, to modify one line in a file, you have to overwrite and rewrite the entire file.)

#!/usr/bin/env python2.7
import re

def find_and_modify(config_file, given_string):

    with open(config_file) as f:
        lines = f.readlines()

    given_string_re = re.compile(r'# for .*{}'.format(given_string))

    # line #'s that start with either "export" or "#export"
    export_line_numbers = []
    # the line # containing the given_string we're searching for
    uncomment_line_number = None

    for i,line in enumerate(lines):
        if re.match(r'#?export', line):
            export_line_numbers.append(i)
            prev_line = lines[i-1]
            if given_string_re.match(prev_line):
                uncomment_line_number = i

    for i in export_line_numbers:
        if i == uncomment_line_number:
            lines[i] = re.sub(r'^#*', '', lines[i])
        else:
            lines[i] = re.sub(r'^#*', '#', lines[i])

    with open(config_file, 'w') as f:
        f.writelines(lines)

find_and_modify('some_file', 'AAA')
find_and_modify('some_file', 'CcC')
梦幻之岛 2024-10-05 04:33:42

首先创建一个生成器函数:

import re
def uncomment(seq, prev_pattern, curr_pattern):
    """Remove comment from any string in seq matching curr_pattern if the previous line matches prev_pattern"""
    prev = ""
    for curr in seq:
        if re.match(curr_pattern, curr) and re.match(prev_pattern, prev):
            yield curr[1:]
    else:
       yield curr
    prev = curr

现在测试它:

>>> lines = ["leave this alone", "#fix next line", "#fix this line", "leave this alone"]
>>> print "\n".join(uncomment(lines, "^#fix next", "^#fix this"))
leave this alone
#fix next line
fix this line
leave this alone

现在使用它来修复您的文件:

with open(input_filename, 'r') as f_in:
    with open(output_filename, 'w') as f_out:
        for line in uncomment(f_in, "^#for AAA", "^#export CONFIG"):
            f_out.write(line)

First create a generator function:

import re
def uncomment(seq, prev_pattern, curr_pattern):
    """Remove comment from any string in seq matching curr_pattern if the previous line matches prev_pattern"""
    prev = ""
    for curr in seq:
        if re.match(curr_pattern, curr) and re.match(prev_pattern, prev):
            yield curr[1:]
    else:
       yield curr
    prev = curr

Now test it:

>>> lines = ["leave this alone", "#fix next line", "#fix this line", "leave this alone"]
>>> print "\n".join(uncomment(lines, "^#fix next", "^#fix this"))
leave this alone
#fix next line
fix this line
leave this alone

Now use it to fix your file:

with open(input_filename, 'r') as f_in:
    with open(output_filename, 'w') as f_out:
        for line in uncomment(f_in, "^#for AAA", "^#export CONFIG"):
            f_out.write(line)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文