词组删除脚本正在删除给定短语中的所有字符

时间:2018-08-12 02:10:02

标签: python python-3.x file input raw-input

我制作了一个python脚本,该脚本应该可以自动从指定的文本文件中删除词组。问题在于,不仅仅是删除该短语。它也删除了该短语包含的字母。

示例

下面是一个测试文件。我要用我的脚本删除其中每个单词“ python”的实例。

Screenshot of file to clean

现在我将运行脚本。

Screenshot of script being ran.

让我们看一下输出文件。

Screenshot of "cleaned" file

脚本代码

infile = input('Enter your file location: ')
outfile = "cleaned"

delete_list = input("What phrase would you like to remove from your file? ")
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
    for word in delete_list:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()

是什么原因造成的?感谢您提前提供的帮助:)

PS我正在运行Python 3

2 个答案:

答案 0 :(得分:1)

只需在输入行添加.split()。这使您可以获得要迭代并删除的输入单词的列表。

delete_list = input("What phrase would you like to remove from your file? ").split()

答案 1 :(得分:0)

@JohnGordon在评论中已经给出了正确的答案,但这只是一个简单的示例:

infile = input('Enter your file location: ')
outfile = "cleaned"
delete_list = input("What phrase would you like to remove from your file? ").split()
with open(infile,'r') as f,open(outfile,'w') as f2:
   a=f.read()
   for i in delete_list:
      a=a.replace(i,'')
   f2.write(a)