【问题标题】:Python, writing two codes within one codePython,在一个代码中编写两个代码
【发布时间】:2022-01-19 05:53:09
【问题描述】:

输入:

ID   information1
Aa   information1-1
CC   information1-2
Ca   Homo sapiens
Da   information1-4
//
ID   information2
Aa   information2-1
CC   information2-2
Ca   information2-3
Da   information2-4
//

预期输出:

ID   information1
Aa   information1-1
Ca   Homo sapiens
Da   information1-4
//

代码1:

# Step1
with open(input_file, 'r') as input, open('temp.txt', 'w') as temp:

    for line in input: 

        if not line.startswith('CC   '):
            temp.write(line)

代码2:

# Step2
word = 'Homo sapiens'
with open('temp.txt', 'r') as input, open(output_file, 'w') as output:

    for block in input.read().split('//'):

        if word in block:
        
            output.write(block)
            output.write('//')

我想在一个代码中执行两个步骤,而不是两个单独的代码。有什么建议给我吗?!

【问题讨论】:

  • “一个代码中的两个代码/步骤”是什么意思?请edit 澄清。如需更多提示,请参阅How to Ask
  • “这些代码彼此运行良好” -- 怎么样? output_from_Step1 未定义,input 是文件对象,因此不可调用。
  • 好的,很酷。所以你想按行过滤,按块过滤。您是否已经尝试过将它们结合起来?可以line.startswith('CC ') and word in line吗?
  • 1) 我的意思是,您是否已经尝试过任何方法来结合这两个步骤?对我来说,它看起来很简单,所以我不确定你面临什么问题。 2)那没有回答我的问题。让我改写一下,如果有帮助的话:一行是否有可能以'CC ' 开头包含word

标签: python for-loop if-statement merge block


【解决方案1】:

您可以通过在逐行读取输入时构建潜在输出行的“块”来一次性完成此操作。考虑一下:

word = 'Homo sapiens'
infile = 'blockin.txt'
outfile = 'blockout.txt'

with open(infile) as txtin, open(outfile, 'w') as txtout:
    block = []
    useblock = False
    for line in txtin:
        if line.startswith('//'):
            if useblock:
                block.append(line)
                txtout.write(''.join(block))
                useblock = False
            block = []
        elif not line.startswith('CC   '):
            block.append(line)
            if not useblock and word in line:
                useblock = True

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 2021-05-19
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多