2013-10-02 54 views
0

我想在文件中刪除一些出現的單詞「name」,而不是其他單詞。我猜測最好的方法是使用某種累加器模式,但我不知道如何實現它。刪除txt文件中每一個單詞的第二次出現(Python)

到目前爲止,我有:

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

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

我只是用「考特尼」在文件中的實際名稱的例子。我想以某種方式刪除每個單詞「Courtney」,但不是偶數,即number.count迭代它將「Courtney」的每個實例賦予一個數字值,然後某些代碼刪除單詞「Courtney」的出現,它具有1,3,5,7的價值...

感謝您的幫助,

蓬鬆

+0

如果你做一個for循環來搜索字符串,就像在這個答案中一樣:http://stackoverflow.com/questions/2768628/iterating-through-string-word-at-a-time-in-python ?rq = 1 然後,您可以跟蹤是否刪除了姓氏,並選擇刪除您正在使用的姓氏。 – darthbith

+0

謝謝您的鏈接。這很有幫助,我可以看到它將如何使用,但我認爲我自己對編程的理解還爲時過早。我可能試圖做一些太複雜的事情,因爲我只在編程/ python工作了幾個月。 – Ben

+0

試試吧!最糟糕的情況是什麼?如果您遇到錯誤,請將您正在嘗試的代碼和錯誤發佈到此處,並且人們會很樂意爲您提供幫助(當然,在您做了一些研究並嘗試自行修復之後)。正如你的問題所表達的那樣,它可能會因爲它不夠具體而被關閉...... – darthbith

回答

2

沒有測試,但你可以嘗試這樣的正則表達式:

import re 

with open("old_text.txt") as f: 
    txt = f.read() 
    new_txt=re.sub(r'(\bCourtney\b.*?)(\s*\Courtney\b\s*)','\1',txt,re.S) 

如果你想要一個動態字符串(即,有一個變量在它):

import re 

name='Courtney' 

with open("old_text.txt") as f: 
    txt = f.read() 
    new_txt=re.sub(r'(\b{}\b.*?)(\s*\{}\b\s*)'.format(name,name),'\1',txt,re.S) 
1

這是醜陋的,但它的工作原理,它是純Python

文件names.txt(我已經把號碼名稱考特尼面前更容易休耕哪些被刪除):

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) 

我希望這有助於。隨意問,如果你不明白的東西。

相關問題