2016-08-06 15 views
1

テキストファイルからすべてのURLを削除する必要があります。私はファイルを読んで、私は行ごとに反復して、きれいなファイルを書きます。しかし、以下のコードは変な動作をします。元のファイルの最初の行を削除し、合計で新しい3行を追加します。最も重要なのは、URLを削除しないことです。テキストファイルからURLを削除する

import sys 
import re 

sys.stdout = open('text_clean.txt', 'w') 

with open("text.txt",encoding="'Latin-1'") as f: 
    rep = re.compile(r""" 
         http[s]?://.*?\s 
         |www.*?\s 
         |(\n) 
         """, re.X) 
    non_asc = re.compile(r"[^\x00-\x7F]") 
    for line in f: 
     non = non_asc.search(line) 
     if non: 
      continue 
     m = rep.search(line) 
     if m: 
      line = line.replace(m.group(), "") 
      if line.strip(): 
       print(line.strip())  
+2

なぜstdoutを上書きしますか?あなたはそれを必要としません –

答えて

0

あなたが正規表現で "" と一致するものがすべて置き換えることができ、それはそれを私が使用

import re 
new_file = open('text_clean.txt', 'w') 
with open("text.txt",encoding="'Latin-1'") as f: 
    text = re.sub(r'(?:(?:http|https):\/\/)?([-a-zA-Z0-9.]{2,256}\.[a-z]{2,4})\b(?:\/[[email protected]:%_\+.~#?&//=]*)?',"",f.read(),flags=re.MULTILINE) 
    text = '\n'.join([a for a in text.split("\n") if a.strip()]) 
    new_file.write(text) 

new_file.close() 

試験例を行うには、おそらく最も効率的な方法です:

asdas 
d 
asd 
asd 
https://www.google.com 
http://facebook.com 
facebook.com 
google.com 
dasd.asdasd.asd //this is url too ? 

出力:

asdas 
d 
asd 
asd 
//this is url too ? 
+0

それはまさに前のものがしたものです。 1行目が削除され、テキストファイルの総行数に2行が追加され、httpのURLはすべて削除されません。 – ganesa75

+0

あなたは私たちに入力ファイル –

+0

の例を教えていただけますか?今編集しました: –

関連する問題