2017-02-06 6 views
-1

Problem:Erstellen von Dokumentindex von Wortpositionen

ich Indizierung ausführen soll durch eine Datenstruktur in Python zu schaffen, die alle Wörter aus einer bestimmten Textdatei gespeichert werden und wird auch seine Zeilennummern speichern (alle Zeilen, in denen diese Wörter erscheinen) und auch die Position des Wortes (Spalte #) in dieser bestimmten Zeile.

Bis jetzt kann ich die Wörter im Wörterbuch speichern, indem ich alle Zeilennummern in einer Liste anhefte, aber ich kann ihre Positionen in dieser bestimmten Zeile nicht speichern.

Ich brauche diese Datenstruktur für das schnellere Suchen von Textdateien.

Hier ist mein Code bis jetzt:

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

was das Format von deine Textdatei? – Leonid

+0

@Leonid, Es kann von jedem Format sein. –

+0

@EdwinvanMierlo, ich bin ein Neuling für Python, ich bin nicht in der Lage, gut voranzukommen. –

Antwort

0

Hier einige Code sind die Zeilennummern und Spalten der Worte in Ihrem Textdokument zu speichern:

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)