-2

可能重复:
在python中替换四个字母的单词

我想在 python shell 中编写一个文件,在其中运行一个程序,然后关闭该文件。

这是我现在拥有的代码。

def censor(fileName):
    file = open(fileName, "r")
    for i in len(myList):
        censoredFile = open("censored.txt", "w")
        outputFile.write(censoredFile)
    outputFile.close()

我要运行的程序还没有在程序中,因为我只是想弄清楚如何处理文件。我有一些编程经验,但文件不多。任何输入将不胜感激。

谢谢!

4

2 回答 2

0

这是您需要读取文件,替换所有四个字母单词并将最终结果写入不同文件所需的代码。

def censor(fileName):
    output_content = ""
    with open(fileName, "r") as input_file:
        with open("censored.txt", "w") as output_file:
            output_content = ""
            for line in input_file:
                output_content += ' '.join([word if len(word) != 4 else "****" for word in line.split(" ")])
            output_file.write(output_content)

应该是这样。

于 2012-11-08T23:17:20.073 回答
0
def censor(fileName):
    censoredFile = open("censored.txt", "w")
    for line in open(fileName, "r"):
        censoredLine= do_stuff_to_censor_line(line)
        censoredFile.write(censoredLine)

简单地说,这里是函数的作用:

1. open the output file

2. go through the input file... for each line:
   2.1 figure out what the censored version of the line would be
   2.2 write the censored version of the line to the output file

3. close both files (this happens automatically so you dont actually have to call close()

现在对于一行的实际审查...如果您想正确审查内容,仅查看 4 个字母的单词可能还不够强大。这是因为并非所有的顽皮词都是四个字母长。还有一些不调皮的词是四个字母长[例如:'four','long','want','this','help']

def do_stuff_to_censor_line(line):
    list_of_naughty_words = ['naughty_word_1','naughty_word_2','etc']
    for naughty_word in list_of_naughty_words:
        line.replace(naughty_word,'*$#@!')
    return line

我将由您来处理不同的大小写...

于 2012-11-08T23:19:32.930 回答