テキストファイルからすべての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())
なぜstdoutを上書きしますか?あなたはそれを必要としません –