0

「test.txt」には2つのsentnecがあります

文 1 = 文は、1 つまたは複数の単語で構成される文法単位です。

文2 =文は、正書法用語のみで定義することもできます。

count_line = 0
for line in open('C:/Users/Desktop/test.txt'):
    count_line = count_line +1
    fields = line.rstrip('\n').split('\t')
    ##print count_line, fields
    file = open('C:/Users/Desktop/test_words.txt', 'w+')
    count_word = 0
    for words in fields:
        wordsplit = words.split()
        for word in wordsplit:
             count_word = count_word + 1
             print count_word, word
             file.write(str(count_word) + " " + word + '\n')
        file.close()

「test_words.txt」での私の結果は、2 番目の文の単語のみを示しました。

1 A 
2 sentence
3 can
4 also
5 be
6 defined
7 in
8 orthographic
9 terms
10 alone.

最初の文の単語も書き、2 番目の文 "test_words.txt" の単語を続けるにはどうすればよいですか?

なにか提案を?

4

4 に答える 4

3

あなたのコードでは、出力ファイルを何度も開いたり閉じたりしているため、コードは最初の文から書いたものを上書きします。簡単な解決策は、一度だけ開いて一度だけ閉じることです。

count_line = 0
# Open outside the loop
file = open('C:/Users/Desktop/test_words.txt', 'w+')
for line in open('C:/Users/Desktop/test.txt'):
    count_line = count_line +1
    fields = line.rstrip('\n').split('\t')
    ##print count_line, fields
    count_word = 0
    for words in fields:
        wordsplit = words.split()
        for word in wordsplit:
            count_word = count_word + 1
            print count_word, word
            file.write(str(count_word) + " " + word + '\n')
# Also close outside the loop
file.close()
于 2012-12-17T18:42:31.920 に答える
0

可能であれば、withファイルを扱うときに を使用する必要があります。これはコンテキスト マネージャーであり、処理が完了するとファイルが適切に閉じられるようにします (インデントされたブロックを残すことで示されます)。ここでは、指定されenumerateたオプションのstart引数を使用します。これは、カウンターが次の行に移動するときにカウンターを動かし続けるための (いくつかの) 方法の 1 つです。

# Open the file
with open('test.txt', 'rb') as f:
  # Open the output (in Python 2.7+, this can be done on the same line)
  with open('text_words.txt', 'wb') as o:
    # Set our counter
    counter = 1
    # Iterate through the file
    for line in f:
      # Strip out newlines and split on whitespace
      words = line.strip().split()
      # Start our enumeration, which will return the index (starting at 1) and
      # the word itself
      for index, word in enumerate(words, counter):
        # Write the word to the file
        o.write('{0} {1}\n'.format(index, word))
      # Increment the counter
      counter += len(words)

または、より少ない行が必要な場合-これはreadlines()、ファイルを改行で区切られた項目のリストに読み込むために使用します。次に、行自体が空白で分割され、各単語が引き出されます。これは、基本的にファイル内のすべての単語のリストを反復処理することを意味しenumerate、カウンターをインクリメントする必要はありません。

# Open the file
with open('test.txt', 'rb') as f:
  # Open the output (in Python 2.7+, this can be done on the same line)
  with open('text_words.txt', 'wb') as o:
    # Iterate through the file
    for i, w in enumerate((x for l in f.readlines() for x in l.strip().split()), 1):
      o.write('{0} {1}\n'.format(i, w))

Python 2.7 の使用:

# Open the file
with open('test.txt', 'rb') as f, open('text_words.txt', 'wb') as o:
  # Iterate through the file
  for i, w in enumerate((x for l in f.readlines() for x in l.strip().split()), 1):
    o.write('{0} {1}\n'.format(i, w))
于 2012-12-17T18:47:02.407 に答える
0

これが発生する理由は、ファイルを 2 回目に開いたときに、ファイル内の元のテキストが保持されないためです。Python でファイルを開いて書き込みを行うと、変数に格納して書き直さない限り、基本的にその内容は上書きされます。

このコードを試してください:

count_line = 0
for n, line in enumerate(open('test.txt')):
    count_line = count_line +1
    fields = line.rstrip('\n').split('\t')
    ##print count_line, fields
    already_text = open('test_words.txt').read() if n > 0 else ''
    file = open('test_words.txt', 'w+')
    count_word = 0
    file.write(already_text)
    for words in fields:
        wordsplit = words.split()
        for word in wordsplit:
             count_word = count_word + 1
             print count_word, word
             file.write(str(count_word) + " " + word + '\n')
        file.close()

これを実行したときの出力は次のとおりです。

1A
2文
3は
4a
5 文法
6台
7からなる
8の
9 1
10または
11以上
12語。
1A
2文
3缶
4も
5be
6 定義済み
7インチ
8 正書法
9期
一人で10。

なしのコードは次のenumerate()とおりです。

count_line = 0
n = 0
for line in open('test.txt'):
    count_line = count_line +1
    fields = line.rstrip('\n').split('\t')
    ##print count_line, fields
    already_text = open('test_words.txt').read() if n > 0 else ''
    file = open('test_words.txt', 'w+')
    count_word = 0
    file.write(already_text)
    for words in fields:
        wordsplit = words.split()
        for word in wordsplit:
             count_word = count_word + 1
             print count_word, word
             file.write(str(count_word) + " " + word + '\n')
        file.close()
    n += 1
于 2012-12-17T18:27:15.000 に答える
0

これは無関係かもしれませんが、よりクリーンな方法を使用して記述することをお勧めします。あなたは3つのループを持つ必要はありません:

lines = open('test.txt').readlines()
file = open('test_words.txt', 'w+')
for line in lines:
  words = line.rstrip('\n').split()

  for i, word in enumerate(words):
    print i, word
    file.write('%d %s\n' % (i+1, word))
file.close()
于 2012-12-17T18:49:07.563 に答える