-2

重複の可能性:
Python で 4 文字の単語を置き換える

Pythonシェルにファイルを書き込み、その中でプログラムを実行してから、ファイルを閉じます。

ここに私が今持っているコードがあります。

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

これは、ファイルを読み取り、4文字の単語をすべて置き換え、最終結果を別のファイルに書き込むために必要なコードです。

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文字の単語を見るだけではおそらく十分に強力ではありません. これは、すべてのいたずらな単語が 4 文字の長さであるとは限らないためです。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 に答える