我是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))
到目前为止我有这个文件并将其导入列表中,然后我可以从新列表中删除一个单词,但也希望从文本文件中删除该单词。
答案 0 :(得分:1)
这是我推荐的内容,因为它非常简单,我认为你不关心性能。:
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)
会在item
中抛出lst
的第一个实例,而只会抛出第一个实例。因此,item
的第二个实例将免于.remove()
。这就是我的解决方案使用列表推导从列表中排除excludedWord
的所有实例的原因。如果你真的想使用.remove()
,你可以这样做:
while excludedWord in lst:
lst.remove(excludedWord)
但我不鼓励这样做,而是支持等效列表理解
答案 1 :(得分:0)
我们可以替换文件中的字符串(需要一些导入;)):
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'相同。
答案 2 :(得分:0)
因此,我正在尝试类似的操作,以下是可能最终阅读此主题的人员的几点建议。替换修改后的内容的唯一方法是在“ 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)