0

ファイル内の「名前」という単語のいくつかの出現箇所を削除したいのですが、他の出現箇所は削除したくありません。これを行う最善の方法は、ある種のアキュムレータ パターンを使用することだと思いますが、それを実装する方法がわかりません。

これまでのところ、私は持っています:

f = open("old_text.txt")
number = f.read()
f.close

name_occurrence = (number.count("Courtney"))

ファイル内の実際の名前の例として「Courtney」を使用しています。「Courtney」という単語の奇数回の出現はすべて削除したいと思いますが、偶数回の単語は削除したくありません。つまり、number.count反復するときに「Courtney」の各インスタンスに数値を割り当ててから、値を持つ「Courtney」という単語の出現を削除するコードがあります。 1,3,5,7...の

ご協力いただきありがとうございます、

ふわふわ

4

2 に答える 2

1

これは醜いですが、動作し、純粋な python です

ファイルnames.txt(Courtney という名前の前に番号を付けて、どれが削除されたかを簡単に確認できるようにしました):

11111 Courtney Emma Jessica 22222 Courtney Ashley Amanda Jennifer 
Sarah Michael 33333 Courtney Christopher Matthew Joshua David
Emma Jessica Ashley Amanda Jennifer 44444 Courtney 
Sarah 55555 Courtney Michael 66666 Courtney Christopher 
77777 Courtney Emma Jessica Ashley Amanda Jennifer 88888 Courtney 
Sarah Michael 99999 Courtney Christopher Matthew

コード:

f = open("names.txt",'r')
splited_lines = []
name_occurrence = 0
name = "Courtney"

#create list of lines where line is list of words
index = 1
for line in f:
    name_occurrence += line.count(name)
    splited_line = line.split()
    splited_lines.append(splited_line)
f.close

#delete every even name (Courtney)
#if you want every odd to be deleted set word_counter on 0
word_counter = -1    
for i,line in enumerate(splited_lines):
    for j,word in enumerate(line):
        if (name in word):
            word_counter += 1 
            if (word_counter%2 == 0):
                splited_lines[i][j] = word.replace(name, "")

#create string to write back to file
text_to_save = ""
for line in splited_lines:
    for word in line:
        if word != "":
            text_to_save += word + " "
    text_to_save += "\n"

#write to file
with open('names.txt', 'w') as f:
    f.writelines(text_to_save)

これが役立つことを願っています。わからないことがあれば遠慮なく聞いてください。

于 2013-10-03T11:09:46.917 に答える