从文件中删除单词并将其余部分保存到同一文件
deleting words from a file and saving the rest to the same file
我有一个小问题
我希望将所有删除的单词上传到我犯错的同一个文件中:D
infile = "tada.txt"
outfile = "tada.txt"
word = "vul"
tada=(''.join(word))
delete_list = tada
with open(infile) as fin, open(outfile, "w+") as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
来自文本
this is vul great
如果文件中有单词vul
输出是
this is great
所以我希望相同的输出在同一个文件中
但问题是脚本删除了所有内容,文件仍然是空的
您可以使用 Python 的 fileinput
模块有效地“就地”更改文件。这是它如何用于您想要的(即从每一行中删除单词)。
注意,与您的代码不同,以下内容将删除整个 个单词,而不是每行中的一个字母。
import fileinput
filepath = "tada.txt"
banned = {"bfd", "vul", "wtf"} # Disallowed words.
with fileinput.input(files=filepath, inplace=True) as file:
for line in file:
words = [word for word in line.split() if word.lower() not in banned]
print(' '.join(words))
我有一个小问题
我希望将所有删除的单词上传到我犯错的同一个文件中:D
infile = "tada.txt"
outfile = "tada.txt"
word = "vul"
tada=(''.join(word))
delete_list = tada
with open(infile) as fin, open(outfile, "w+") as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
来自文本
this is vul great
如果文件中有单词vul
输出是
this is great
所以我希望相同的输出在同一个文件中
但问题是脚本删除了所有内容,文件仍然是空的
您可以使用 Python 的 fileinput
模块有效地“就地”更改文件。这是它如何用于您想要的(即从每一行中删除单词)。
注意,与您的代码不同,以下内容将删除整个 个单词,而不是每行中的一个字母。
import fileinput
filepath = "tada.txt"
banned = {"bfd", "vul", "wtf"} # Disallowed words.
with fileinput.input(files=filepath, inplace=True) as file:
for line in file:
words = [word for word in line.split() if word.lower() not in banned]
print(' '.join(words))