2

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]
4

4 に答える 4

3

これで、あなたが望むものを達成できるはずだと私は信じています。

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

fnameファイルの場所を指す変数を次に示します。

于 2013-05-29T07:07:44.367 に答える
1

あなたはあなたの機能でほとんどそこにいました。:行がそれで終わっているかどうかを確認する必要があるときに、行のどこかに表示されているかどうかを確認していました。

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ステートメントはコンテキストを作成し、ブロックが終了するとファイルを自動的に閉じます。

于 2013-05-29T07:12:15.287 に答える
0

正規表現を使用できます

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)
于 2013-05-29T10:46:44.837 に答える
0

最後の文字が であるかどうかを検索するには: 次の手順を実行します。

if line.strip().endswith(':'):
    ...Do Something...
于 2013-05-29T07:01:00.527 に答える