【问题标题】:Censor Words from a File Using a CensorFile - Python使用 CensorFile 审查文件中的单词 - Python
【发布时间】:2014-05-08 01:52:28
【问题描述】:

我正在尝试创建一个“审查员”程序,该程序会在“审查员列表”中读取要审查出“审查员文件”的词语。我觉得我很接近了,但是当我运行程序时,它只会审查一行。任何帮助将不胜感激!

#!/usr/bin/python

import sys, os

censorlist = raw_input("File with words to censor? ")
if os.path.isfile(censorlist):
  print "The file", censorlist, "exists!"
else:
  print "The file", censorlist, "doesn't exist!"
  sys.exit()
  print ""

filterword = {}
for currentline in censorlist:
  line = currentline.strip()
  filterword.append(line)

censorfile = raw_input("File to censor using provided list? ")
script = []
for currentline in censorfile:
  line = currentline.strip()
  script.append(line)

for lines in script:
  results = []
  words = lines.split()
  for word in words:
    if word in filter:
      results.append("****")
    else:
      results.append(word)

resultfile = open(censorfile, 'w')
for items in results:
    resultfile.write(items)

【问题讨论】:

  • 您不需要发布整个程序,只需发布​​您正在努力解决的问题。解释不清楚,代码有问题。您将字符串分配给censorlist,然后使用for currentline in censorlist 对其进行迭代,但您要迭代的不是行,而是字符。
  • 您是在问如何用**** 替换一堆子字符串?如果是这样,请查看以字符串形式读取文件,然后执行for word in censorlist: inputfile.replace(word, '****')。祝你好运。
  • 对不起,我不清楚。我正在尝试从 censorlist 中获取单词,并且每次它们出现在 censorfile 中时,将单词(在 censorfile 中)替换为 ****
  • @user3284938 不应该 filterword 是一个数组而不是一个对象?您正在对一个对象使用 append。

标签: python filter


【解决方案1】:

您只需使用字符串的replace 方法来替换子字符串的每个实例...

'foo bar spam foo'.replace('foo', '****') # '**** bar spam ****'

您只需要遍历要审查的单词列表并为每个单词调用replace

for word in censorlist:
    string.replace(word, '****')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2015-03-10
    • 2015-12-08
    • 2013-02-02
    • 2017-11-15
    • 2015-09-27
    相关资源
    最近更新 更多