简体   繁体   English

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

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

Input.txt File Input.txt文件

12626232 : Bookmarks 
1321121:
126262   

Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line 126262:可以是任何文本或数字,因此基本上将搜索最后一个单词为:(冒号)并删除整行

Output.txt File Output.txt文件

12626232 : Bookmarks 

My Code: 我的代码:

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()

Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line. 问题:当我与匹配时,它会删除整行,但是我只想检查它是否存在于行尾,如果它在行尾,则只删除整行。 Any suggestion will be appreciated. 任何建议将不胜感激。 Thanks. 谢谢。

I saw as following but not sure how to use it in here 我看到以下内容,但不确定如何在此处使用

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

I believe with this you should be able to achieve what you want. 我相信,您应该能够实现您想要的。

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

Here fname is the variable pointing to the file location. fname是指向文件位置的变量。

You were almost there with your function. 您的功能几乎在那里。 You were checking if : appears anywhere in the line, when you need to check if the line ends with it: 您需要检查:出现在行中的任何地方,何时需要检查行是否以它结尾:

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()

You could have also done if not line.strip()[:-1] == ':': , but endswith() is better suited for your use case. if not line.strip()[:-1] == ':':也可以这样做,但是endswith()更适合您的用例。

Here is a compact way to do what you are doing above: 这是一种执行上面操作的紧凑方法:

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)

The with statement creates a context and automatically closes files when the block ends. with语句创建上下文,并在块结束时自动关闭文件。

To search if the last letter is : Do following 要搜索最后一个字母是否为:请执行以下操作

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

You can use a regular expressio n 您可以使用正则表达式

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