【问题标题】:Phrase removal script is removing all characters in the phrase given短语删除脚本正在删除给定短语中的所有字符
【发布时间】:2019-01-19 04:05:19
【问题描述】:

我制作了一个 Python 脚本,它应该能够自动从指定的文本文件中删除一个短语。问题是它不仅仅是删除短语。它也删除了短语中包含的字母。

示例

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

现在我将运行我的脚本。

让我们看一下输出文件。

脚本代码

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

【问题讨论】:

  • for word in delete_list 循环遍历短语中的每个字符,而不是每个单词。请改用for word in delete_list.split():
  • @JohnGordon 只是好奇,您为什么要在 cmets 中发布答案?我见过很多人这样做。
  • @TheTesseract'sShadow 通常我只是有建议,而不是完全充实的答案,所以我已经习惯了评论。
  • 由于某些原因,它也激怒了我@TheTesseract'sShadow

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


【解决方案1】:

评论中的@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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多