[英]Deleting a specific word from a file in python
我對 python 很陌生,剛剛開始導入文本文件。 我有一個包含單詞列表的文本文件,我希望能夠輸入一個單詞並將該單詞從文本文件中刪除。 誰能解釋我該怎么做?
text_file=open('FILE.txt', 'r')
ListText = text_file.read().split(',')
DeletedWord=input('Enter the word you would like to delete:')
NewList=(ListText.remove(DeletedWord))
到目前為止,我有這個文件並將其導入列表,然后我可以從新列表中刪除一個單詞,但也想從文本文件中刪除該單詞。
這是我的建議,因為它相當簡單,我認為您不關心性能。:
f = open("file.txt",'r')
lines = f.readlines()
f.close()
excludedWord = "whatever you want to get rid of"
newLines = []
for line in lines:
newLines.append(' '.join([word for word in line.split() if word != excludedWord]))
f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()
這允許一行上有多個單詞,但如果每行只有一個單詞,它也能正常工作
回應更新的問題:
您不能直接編輯文件(或者至少我不知道如何),而是必須在 Python 中獲取所有內容,對其進行編輯,然后使用更改后的內容重新編寫文件
另一件事要注意, lst.remove(item)
將拋出lst
中item
的第一個實例,並且只拋出第一個。 所以item
的第二個實例對.remove()
是安全的。 這就是為什么我的解決方案使用列表理解為排除的所有實例excludedWord
從列表中。 如果你真的想使用.remove()
你可以做這樣的事情:
while excludedWord in lst:
lst.remove(excludedWord)
但我不鼓勵這樣做,以支持等效的列表理解
我們可以替換文件中的字符串(需要一些導入;)):
import os
import sys
import fileinput
for line in fileinput.input('file.txt', inplace=1):
sys.stdout.write(line.replace('old_string', 'new_string'))
在這里找到這個(也許): http : //effbot.org/librarybook/fileinput.htm
如果'new_string' 更改為'',則這與刪除'old_string' 相同。
所以我在嘗試類似的東西,這里有一些要點給可能最終閱讀這個線程的人。 您可以替換修改后的內容的唯一方法是以“w”模式打開相同的文件。 然后python只是覆蓋現有文件。 我使用“re”和 sub() 嘗試了這個:
import re
f = open("inputfile.txt", "rt")
inputfilecontents = f.read()
newline = re.sub("trial","",inputfilecontents)
f = open("inputfile.txt","w")
f.write(newline)
@Wnnmaw 你的代碼有點錯誤,應該是這樣的
f = open("file.txt",'r')
lines = f.readlines()
f.close()
excludedWord = "whatever you want to get rid of"
newLines = []
for line in newLines:
newLines.append(' '.join([word for word in line.split() if word != excludedWord]))
f = open("file.txt", 'w')
for line in lines:
f.write("{}\n".format(line))
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.