2012-12-21 115 views
2

在test.txt的:如何替換文件中的單詞?

rt : objective 
tr350rt : objective 
rtrt : objective 
@username : objective 
@user_1236 : objective 
@254test!! : objective 
@test : objective 
#15 : objective 

我的代碼:

import re 
file3 = 'C://Users/Desktop/test.txt' 
rfile3 = open(file3).read() 
for altext in rfile3.split("\n"): 
    saltext = altext.split("\t") 
    for saltword in saltext: 
     ssaltword = saltword.split(" ") 
     if re.search(r'^rt$', ssaltword[0]): 
     print ssaltword[0], ssaltword[2] 
     testreplace = open(file3, 'w').write(rfile3.replace(ssaltword[0], "")) 
     if re.search(r'^@\w', ssaltword[0]): 
      print ssaltword[0], ssaltword[2] 
     testreplace = open(file3, 'w').write(rfile3.replace(ssaltword[0], "")) 

我:

: objective 
tr350 : objective 
: objective 
@username : objective 
@user_1236 : objective 
@254test!! : objective 
: objective 
#15 : objective 

我試圖取代只有 「RT」,所有與@空間

但從我的代碼中,所有「rt」被替換,只有一個@被替換。

我想獲得:

: objective 
tr350rt : objective 
rtrt : objective 
: objective 
: objective 
: objective 
: objective 
#15 : objective 

什麼建議嗎?

回答

2

我覺得正則表達式是矯枉過正這裏:

with open("test.txt") as in_fp, open("test2.txt", "w") as out_fp: 
    for line in in_fp: 
     ls = line.split() 
     if ls and (ls[0].startswith("@") or ls[0] == "rt"): 
      line = line.replace(ls[0], "", 1) 
     out_fp.write(line) 

產生

localhost-2:coding $ cat test2.txt 
: objective 
tr350rt : objective 
rtrt : objective 
: objective 
: objective 
: objective 
: objective 
#15 : objective 

請注意,我也改變了它不覆蓋原來的。

編輯:如果你真的想覆蓋就地原,然後我讀了整個事情到內存第一:

with open("test.txt") as fp: 
    lines = fp.readlines() 

with open("test.txt", "w") as out_fp: 
    for line in lines: 
     ls = line.split() 
     if ls and (ls[0].startswith("@") or ls[0] == "rt"): 
      line = line.replace(ls[0], "", 1) 
     out_fp.write(line) 
+0

對不起,我不熟悉「with open」。我必須覆蓋原始文件,然後使用「in_fp.write 「),對嗎? – ThanaDaray

+1

請考慮讓帝斯曼的建議不要覆蓋原始文件;這幾乎總是可取的。一旦你確定你的代碼正在工作,你可以在最後添加一點刪除原來的文件並重命名新的匹配舊名稱。 'with open'語法只是意味着Python會打開該文件,但只會在下面的範圍內保持打開狀態。只要代碼縮進),然後自動關閉它。 –

+0

@DSM非常感謝。 – ThanaDaray

1
import re 
with open("test.txt") as infile: 
    text = infile.read() 
    newtext = re.sub(r"(?m)^(?:rt\b|@\w+)(?=\s*:)", " ", text) 

說明:

(?m)  # Turn on multiline mode 
^   # Match start of line 
(?:  # Either match... 
rt\b  # rt (as a complete word 
|   # or 
@\w+  # @ followed by an alphanumeric "word" 
)   # End of alternation 
(?=\s*:) # Assert that a colon follows (after optional whitespace) 
+0

我試過了,沒有改變。 – ThanaDaray

+0

@ThanaDaray:你看過'newtext'嗎?你需要把它寫入你的(新的)文件中:'open(「newfile.txt」,「w」outfile:outfile.write(newtext)' –

+0

+1正則表達式解釋 – naiquevin

1

試試這個,

import os 

mydict = {"@":'',"rt":''} 

filepath = 'C://Users/Desktop/test.txt' 
s = open(filepath).read() 
for k, v in mydict.iteritems(): 
    s = s.replace(k, v) 
f = open(filepath, 'w') 
f.write(s) 
f.close() 
+1

'import ''語句在這裏?你沒有使用'walk'或任何其他'os'函數 –

+1

我喜歡這種模式,但我認爲它不適用於OP的情況,因爲我們不是簡單地刪除'@'符號,但以@開頭的字 – DSM

+0

@KyleStrand謝謝,更新 –

1

甚至沒有必要在這裏使用正則表達式:

with open("test.txt") as file: 
    lines = file.readlines() 
    for line in lines: 
     if (line.startswith("@") and ":" in line) or line.startswith("rt :"): 
      line = " :" + line.split(":", 1)[1] 
+1

正則表達式解決方案很少是更好的解決方案。 – mmgp

+0

原始問題比您處理的簡單「rt:」情況具有更復雜的刪除「rt」實例。 –

+0

根據他在OP上的想要的輸出,這工作正常。閱讀OP上的「我想獲得:」部分。 – 2012-12-21 16:25:24