繁体   English   中英

匹配最后一个单词并删除整行

[英]Match the last word and delete the entire line

Input.txt文件

12626232 : Bookmarks 
1321121:
126262   

126262:可以是任何文本或数字,因此基本上将搜索最后一个单词为:(冒号)并删除整行

Output.txt文件

12626232 : Bookmarks 

我的代码:

def function_example():
    fn = 'input.txt'
    f = open(fn)
    output = []
    for line in f:
        if not ":" in line:
            output.append(line)
    f.close()
    f = open(fn, 'w')
    f.writelines(output)
    f.close()

问题:当我与匹配时,它会删除整行,但是我只想检查它是否存在于行尾,如果它在行尾,则只删除整行。 任何建议将不胜感激。 谢谢。

我看到以下内容,但不确定如何在此处使用

a = "abc here we go:"
print a[:-1]

我相信,您应该能够实现您想要的。

with open(fname) as f:
    lines = f.readlines()
    for line in lines:
        if not line.strip().endswith(':'):
            print line

fname是指向文件位置的变量。

您的功能几乎在那里。 您需要检查:出现在行中的任何地方,何时需要检查行是否以它结尾:

def function_example():
    fn = 'input.txt'
    f = open(fn)
    output = []
    for line in f:
        if not line.strip().endswith(":"):  # This is what you were missing
            output.append(line)
    f.close()
    f = open(fn, 'w')
    f.writelines(output)
    f.close()

if not line.strip()[:-1] == ':':也可以这样做,但是endswith()更适合您的用例。

这是一种执行上面操作的紧凑方法:

def function_example(infile, outfile, limiter=':'):
    ''' Filters all lines in :infile: that end in :limiter:
        and writes the remaining lines to :outfile: '''

    with open(infile) as in, open(outfile,'w') as out:
       for line in in:
         if not line.strip().endswith(limiter):
              out.write(line)

with语句创建上下文,并在块结束时自动关闭文件。

要搜索最后一个字母是否为:请执行以下操作

if line.strip().endswith(':'):
    ...Do Something...

您可以使用正则表达式

import re

#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"

with open(file_name) as _file:
    lines = _file.readlines()
    new_lines = [line for line in lines if regex.search(line.strip())]

with open(file_name, "w") as _file:
    _file.writelines(new_lines)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM