如何在python中執行此操作?從基於另一個文件的文件中刪除短語(Python)
badphrases.txt包含
Go away
Don't do that
Stop it
allphrases.txt包含
I don't know why you do that. Go away.
I was wondering what you were doing.
You seem nice
我想allphrases.txt是乾淨的badphrases.txt的線條。
這是在bash
cat badfiles.txt | while read b
do
cat allphrases.txt | grep -v "$b" > tmp
cat tmp > allphrases.txt
done
哦瑣碎的,你以爲我沒有看或審判。我搜索了一小時。
這裏是我的代碼:
# Files
ttv = "/tmp/tv.dat"
tmp = "/tmp/tempfile"
bad = "/tmp/badshows"
Badfiles文件已經存在
...代碼就在這裏創建TTV
# Function grep_v
def grep_v(f,str):
file = open(f, "r")
for line in file:
if line in str:
return True
return False
t = open(tmp, 'w')
tfile = open(ttv, "r")
for line in tfile:
if not grep_v(bad,line):
t.write(line)
tfile.close
t.close
os.rename(tmp, ttv)
還不如請求用戶google「如何用python替換文件中的行」。 –
可能有100種方法可以做到這一點。顯然他/他正在嘗試學習python。所以給出一些基本的提示。 –
有時事情在另一種語言中更容易。無論python中的解決方案是什麼,它肯定比它需要的複雜得多。我不明白爲什麼python很受歡迎。 –