2016-12-01 96 views
0

我希望能收到一些關於我在Python 3中編寫的代碼的一些反饋 - 我試圖編寫一個程序來讀取其中包含頁碼的輸入文件。頁碼格式爲:「[13]」(這意味着你在第13頁)。我的代碼現在的問題是:查找並從行中刪除特定的字符串

pattern='\[\d\]' 

for line in f: 
if pattern in line: 
    re.sub('\[\d\]',' ') 
    re.compile(line) 
    output.write(line.replace('\[\d\]', '')) 

我也曾嘗試:

​​

當我運行這些程序,一個空白文件被創建,而不是包含原始文本減去頁碼的文件。提前感謝您的任何建議!

回答

1

你的if語句不起作用,因爲沒有進行正則表達式匹配,它正在尋找\[\d\]的文字字符串line

for line in f: 
    # determine if the pattern is found in the line 
    if re.match(r'\[\d\]', line): 
     subbed_line = re.sub(r'\[\d\]',' ') 
     output_file.writeline(subbed_line) 

此外,您錯誤地使用了re.compile()。它的目的是將你的模式預編譯成一個函數。如果您使用該模式的次數會提高性能,因爲您只評估一次表達式,而不是每次循環時重新評估一次。

pattern = re.compile(r'\[\d\]') 

if pattern.match(line): 
    # ... 

最後,你是因爲你使用output_file.write()其中將一個字符串作爲整個文件得到一個空白文件。相反,您希望使用output_file.writeline()將行寫入文件。

0

您不會將未修改的行寫入輸出。

嘗試這樣的事情

if pattern in line: 
    #remove page number stuff 
output_file.write(line) # note that it's not part of the if block above 

這就是爲什麼你的輸出文件是空的。

相關問題