【问题标题】:Python, how to extract lines containing a specific characterPython,如何提取包含特定字符的行
【发布时间】:2021-12-26 11:00:47
【问题描述】:

输入:

=name Aa Ba Ca DD Ea
sldkclskdf
opkmnbv
=name Ab Bb Cb Db Eb
po,omome
nbnwnejkvjekw
=name Ac Bc Cc DD Ec
lkecvkkw
=name Ad Bd Cd Dd Ed
sdlkcmksldmksd
=name Ae Be Ce DD Ee
clskdjfs

输出:

=name Aa Ba Ca DD Ea
sldkclskdf
opkmnbv
=name Ac Bc Cc DD Ec
lkecvkkw
=name Ae Be Ce DD Ee
clskdjfs

我正在从文件中提取数据。我只想获取包含特定字符(即“DD”)的行以及带有“while 循环”的特定行之后的行信息。

with open(file, 'r') as fr, open(file_modified, 'w') as fw:

    temp = ''
    while(line):
        line = fr.readline()

        if line.startswith('='):
            fw.write(',' + temp + '\n') 

            templist = line.strip().split()
            for element in templist:
                if element.startswith('DD'):
                    fw.write(templist) 

            temp = ''
        else:
            temp += line.strip() 
     
    fw.write(temp)

【问题讨论】:

  • 感谢您的提问。此示例包含两个选项,例如以“=”开头的行及其信息(在特定行的底部)。我想提取包含“DD”的特定行,它是底部的信息。

标签: python find line extract splice


【解决方案1】:

你可以这样做:

INFILE = 'elold.txt'
OUTFILE = 'elnew.txt'
WRITELINE = False

with open(INFILE) as infile:
    with open(OUTFILE, 'w') as outfile:
        for line in infile:
            if line.startswith('='):
                WRITELINE = 'DD' in line
            if WRITELINE:
                outfile.write(line)

【讨论】:

  • 很棒,不需要在一次迭代中“分组”行,只需要“切换”yes-write 或 no-write
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2019-04-03
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多