2017-02-06 5 views
-1

問題作成:ワード位置の文書インデックス

私はPythonでデータ構造を作成することにより、インデックス作成を実行する指定されたテキストファイルからすべての単語を格納しますし、またその行番号を格納します(すべてのそれらの単語が現れる行)とその特定の行の単語(column#)の位置も表示されます。

これまでのところ、すべての行番号をリストに追加して辞書に単語を格納することはできましたが、特定の行にその位置を保存することはできません。

テキストファイルの検索を高速化するには、このデータ構造が必要です。

は、ここまでの今までの私のコードです:ここで

from collections import defaultdict 
thetextfile = open('file.txt','r') 
thetextfile = thetextfile.read() 
file_s = thetextfile.split("\n") 
wordlist = defaultdict(list) 
lineNumber = 0 
for (i,line) in enumerate(file_s): 

    lineNumber = i 
    for word in line.split(" "): 
     wordlist[word].append(lineNumber) 

print(wordlist) 
+0

のフォーマットが何でありますかあなたのテキストファイル? – Leonid

+0

@レオニード、それはどんなフォーマットでもかまいません。 –

+0

@EdwinvanMierlo、私はPythonの初心者です、私はうまくいっていません。 –

答えて

0

あなたのテキストドキュメント内の単語の行番号と列を格納するためのいくつかのコードです:

from collections import defaultdict, namedtuple 

# build a named tuple for the word locations 
Location = namedtuple('Location', 'line col') 

# dict keyd by word in document 
word_locations = defaultdict(list) 

# go through each line in the document 
for line_num, line in enumerate(open('my_words.txt', 'r').readlines()): 
    column = -1 
    prev_col = 0 

    # process the line, one word at a time 
    while True: 
     if prev_col < column: 
      word = line[prev_col:column] 
      word_locations[word].append(Location(line_num, prev_col)) 
     prev_col = column+1 

     # find the next space 
     column = line.find(' ', prev_col) 

     # check for more spaces on the line 
     if column == -1: 

      # there are no more spaces on the line, store the last word 
      word = line[prev_col:column] 
      word_locations[word].append(Location(line_num, prev_col)) 

      # go onto the next line 
      break 

print(word_locations) 
関連する問題