2017-03-31 5 views
0

2つのファイルのすべての行(同時にある種のもの)を繰り返し処理し、そのうちの1つの単語からインデックスを取得する必要があります。ファイルの反復処理と他のファイルからの単語インデックスの取得

例:

small_wordlist:

Book 
Woman 
Child 

big_wordlist:

Book 
Man 
Dog 
Cat 
Child 
Dinosaur 
Woman 

のように。

1 
7 
5 

(私たちは本当に問題ではないこと、0で始まるため、または毎回1以下)と、別のファイルにそれを保存します。 希望の結果は次のようになります。

私はそれがこのようにかなっで動作するように取得することはできません。だから私は、小さなワードリストを反復ビッグワードリストで見つかった単語から特定の単語のインデックスを取得し、それを記述する必要が

g = open('big_wordlist', 'r') 
i = open('index_list', 'w') 

with open('small_wordlist', 'r') as h: 
for line in h: 
    p = h.readline() 
    for num, line in enumerate(g):   # num is my found index 
      if (line.startswith(p + "\n")): # need that to make sure we only get the correct word and nothing before/after it 
       i.write("%s" % (num) + "\n") 

私のインデックスリストに。

私は "ミキシングの繰り返しとデータの読み込み方法が失われる" - インデックスリストにnumを書き込んだ後、p(その時の単語)は変更されますsmall_wordlistのそれぞれの新しい行。

私は小文字の単語リストに対して繰り返しを行うときに問題があります。pを "ブック"に置き換えると、小さな単語リストの各行の単語である変数を使用する必要があります。

+0

「big_wordlist」のサイズはどれくらい大きくできますか? – MooingRawr

+0

ええ、私はできないかもしれませんが、もし私がいなければ、どちらかの方法で幸せになると思います。 – Lightsaber

答えて

1

2つのファイルを同時に処理する必要はありません。代わりに、最初のファイルのインデックスを作成してから、インデックス内の単語を検索する2番目のファイルを処理する必要があります。

#!python3 

small_wordlist = """ 
    Book 
    Woman 
    Child 
""".strip() 

big_wordlist = """ 
    Book 
    Man 
    Dog 
    Cat 
    Child 
    Dinosaur 
    Woman 
""".strip() 

import io 

# Read the words from the big wordlist into word_index 

#with open('big_wordlist.txt') as big: 
with io.StringIO(big_wordlist) as big: 
    ix = 0 
    word_index = {} 

    for line in big: 
     word = line.strip() 
     if word not in word_index: 
      word_index[word] = ix 
     ix += 1 

#with open('small_wordlist.txt') as small: 
with io.StringIO(small_wordlist) as small: 
    for line in small: 
     word = line.strip() 
     if word not in word_index: 
      print('-1') # Or print('not found') or raise exception or... 
     else: 
      print(word_index[word]) 
+0

大きな感謝、それはうまくいく、私は間違った方法だったようだ! – Lightsaber