2017-02-19 4 views
0

テキストファイルをパラメータとして受け取って各単語を含む関数をビルドします単語がテキスト内で出現する行のリストに関連付けられたテキスト。テキストファイルの各単語をファイル内の行のリストにリンクする辞書を作成する

def dictionary(file): 
    in_file=open(file, 'r') 
    words=[] 
    d={} 
    lines=in_file.readlines() 

    for line in lines: 
     words=words+line.split(' ') 

    for j in words: 
     for i in range(len(lines)): 
      if j in lines[i]: 
       d[j]=i 
    return d 

しかし、これはそれだけで(リストではなく)1行のインデックスを示すことから単語が表示される場所、私が欲しかったかなりものではありません。これは私が思いついたものです。 ありがとうございます。

+0

正確に何が欲しいですか?すべての単語とその行番号の辞書? – Arman

+1

これは辞書がどのように機能するか、キーごとに1つの値です。あなたはどんな出力を期待していましたか? – jonrsharpe

+0

あなたが望むならば、各値が数字のリストであるところを作ることができます。あなたは何を望んでいるのですか? – khelwood

答えて

0

辞書の各単語に1つの値の外見を格納するのではなく、リストを保存することができます。別の一致が見つかった場合、これは簡単に更新することができます

ここ
def dictionary(file): 
    in_file=open(ficheiro, 'r') 
    words=[] 
    d={} 
    lines=in_file.readlines() 

    for line in lines: 
     words=words+line.split(' ') 

    for j in words: 
     if (j not in d): 
      d[j] = [] 
      for i in range(len(lines)): 
       if j in lines[i]: 
        d[j].append(i) 
    return d 
+0

これは実際には非常に奇妙な出力を作成します。たとえば、テキストファイルのキー/単語「rabbit」は、「rabbit。」:[12,14,17,12,14,17]という値でリンクされています。他の頻繁な言葉では、リストはかなりの回数繰り返されます。これについての考えは? –

+0

この出力は同じ単語の複数の出現に関連していました。あなたのファイル全体が再び解析されるたびに。したがって、繰り返す。私の答えを更新しました。 – conste

0

は注釈で、あなたが探している何をすべき機能です:

def dictionary(filename): 
    # Pass the function a filename (string) 

    # set up a dict to hold the results 

    result = dict() 

    # open the file and pass it to enumerate 
    # this combination returns something like a list of 
    # (index i.e. line number, line) pairs, which you can 
    # iterate over with the for-loop 

    for idx, line in enumerate(open(filename)): 

     # now take each line, strip any whitespace (most notably, 
     # the trailing newline character), then split the 
     # remaining line into a list of words contained in that line 

     words = line.strip().split() 

     # now iterate over the list of words 

     for w in words: 

      # if this is the first time you encounter this word, 
      # create a list to hold the line numbers within 
      # which this word is found 

      if w not in result: 
       result[w] = [] 

      # now add the current line number to the list of results for this word 

      result[w].append(idx) 

    # after all lines have been processed, return the result 
    return result 

関連機能へのリンク(彼らはwouldn正しく注釈内の「T表示):

open

enumerate

strip

+0

少々の変更とそれは素晴らしい動作します。しかし、私はまだ単なる学習者なので、私は表記に慣れていません。 idx、行列挙(open(f))の行為は何ですか?:: –

+0

もちろん、十分です。アノテーションだけで更新。それが助けてくれることを願っています。 – gary

+0

@Joe - チェックインしました。 – gary

関連する問題