2

私はプログラミングが初めてで、Python スクリプトをいじっています。

テキストファイルを読み取って画面に出力し、単語を検索し、単語が見つかるたびにその行のデータを分割する Python スクリプトを作成しようとしています。

test.txt ファイルは次のようになります。

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar

画面上の最終結果を次のようにしたい:

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar

これまでの私のコード:

file = "test.txt"
read_file = open(file, "r")
with read_file as data:
    read_file.read()
    print(data)
    word = "ape"
    for word in data:
        data.split()
        print(data)

スクリプトで何度も使用するつもりなので、ファイルを変数にしました。

コードをテストしたところ、for ループは 1 回のループで停止しませんでした。最終的には終了しましたが、コードまたはプログラムが自動的に無限ループを終了したのは確かです。

ファイルの最後に到達すると for ループが停止するようにコードを編集するにはどうすればよいですか? そして、このコードを書くためのより正しい方法はありますか?

繰り返しますが、これは単なるサンプル ファイルであり、実際のファイルではありません。ありがとう!

4

7 に答える 7

3
>>> f = open("test.txt")
>>> a = f.read()
>>> f.close()
>>> a = a.replace("ape", "\nape")
>>> print(a)

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar
于 2013-08-20T14:25:39.170 に答える
1

test.txt ファイルは次のようになります。

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar

画面上の最終結果を次のようにしたい:

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar

したがって、「ape」が出現するたびに行頭に配置する必要があります。

これまでの私のコード:

file = "test.txt"
read_file = open(file, "r")
with read_file as data:

この2つを分けても意味がありません。ファイルの処理withが完了すると、ファイルは閉じられ、open()再度編集する必要があります。

だからただする

with open(file, "r") as data:

ところで、あなたのコードでは、read_filedataは同じです。

    read_file.read()

したがって、ファイル全体をメモリに読み込み、結果を破棄します。

    print(data)

ファイル オブジェクトを出力します。

    word = "ape"

割り当て...

    for word in data:

...そしてすぐにもう一度破棄します。

        data.split()

データを分割し、結果を破棄します。

        print(data)

ファイル オブジェクトを再度印刷します。

しかし、ファイル全体を読んだので、forおそらくループはまったく実行されませんでした。

改良点:

filename = "test.txt" # file is a builtin function
hotword = "ape"
with open(filename, "r") as read_file:
    for line in read_file:
        parts = line.split(hotword)
        if not parts[0]: # starts with the hotword, so 1st part is empty
            del parts[0]
        print ("\n" + ape).join(parts)

スクリプトで何度も使用するつもりなので、ファイルを変数にしました。

名前については問題ありませんが、開いているファイルはwith閉じているため、リサイクルできません。

コードをテストしたところ、for ループは 1 回のループで停止しませんでした。

もちろん?それは何を印刷しましたか?

于 2013-08-20T14:48:17.307 に答える
0
import re

file = "test.txt"
for line in open(file, 'r'):
    if(re.search('ape', line )):
        print(line)
于 2013-08-20T14:25:08.113 に答える