2013-02-20 2 views
2

Я пытаюсь сделать индексирование в файл excel, и я использовал whoosh пакет, но i обнаружил ошибку, что индекс списка за пределами допустимого диапазона. , пожалуйста, может ли кто-нибудь мне помочь? мой код:из индекса в python

from whoosh import fields, index 
import os.path 
import csv 
import codecs 

# This list associates a name with each position in a row 
columns = ["juza","chapter","verse","analysis"] 

schema = fields.Schema(juza=fields.NUMERIC, 
         chapter=fields.NUMERIC, 
         verse=fields.NUMERIC, 
         analysis=fields.KEYWORD) 


# Create the Whoosh index 
indexname = "index" 
if not os.path.exists(indexname): 
    os.mkdir(indexname) 
ix = index.create_in(indexname, schema) 

# Open a writer for the index 
with ix.writer() as writer: 
    # Open the CSV file 
    with codecs.open("yom.csv", "rb","utf8") as csvfile: 
    # Create a csv reader object for the file 
    csvreader = csv.reader(csvfile) 

    # Read each row in the file 
    for row in csvreader: 

     # Create a dictionary to hold the document values for this row 
     doc = {} 

     # Read the values for the row enumerated like 
     # (0, "juza"), (1, "chapter"), etc. 
     for colnum, value in enumerate(row): 

     # Get the field name from the "columns" list 
     fieldname = columns[colnum] 

     # Strip any whitespace and convert to unicode 
     # NOTE: you need to pass the right encoding here! 
     value = unicode(value.strip(), "utf-8") 

     # Put the value in the dictionary 
     doc[fieldname] = value 

     # Pass the dictionary to the add_document method 
     writer.add_document(**doc) 
    writer.commit() 
` 

и я получаю эту ошибку и я не знаю, почему? ошибка:

Traceback (most recent call last): 
    File "C:\Python27\yarab.py", line 39, in <module> 
    fieldname = columns[colnum] 
IndexError: list index out of range 

и мой CSV файл:

1 3 1 Al+ POS:ADJ LEM:r~aHoma`n ROOT:rHm MS GEN 
1 3 2 Al+ POS:ADJ LEM:r~aHiym ROOT:rHm MS GEN 
1 4 1 POS:N ACT PCPL LEM:ma`lik ROOT:mlk M GEN 
1 4 2 POS:N LEM:yawom ROOT:ywm M GEN 
1 4 3 Al+ POS:N LEM:diyn ROOT:dyn M GEN 
1 5 1 POS:PRON LEM:&lt;iy~aA 2MS 

ответ

0

csv.reader использует в качестве разделителя по умолчанию запятой: ,

Вы должны определить свой разделитель явно:

csvreader = csv.reader(csvfile, delimiter=...) 

Однако , ваш файл CSV не является однородным , Это будет лучше читать его без csv:

columns = ["juza","chapter","verse","analysis"] 
with codecs.open("yom.csv", "rb","utf8") as f: 
    for line in f: 
     a, b, c, rest = line.split(' ', 3) 
     doc = {k:v.strip() for k,v in zip(columns, rest.split(':'))} 
     # a,b,c are the first three integers 
     # doc is a dictionary 
+0

ли вы имеете в виду, что я должен удалить «CSVReader» и заменить его с предлагаемым кодом? но если я это сделаю, теперь проблема заключается в том, как я могу присвоить имя поля в следующей строке: "fieldname = columns [colnum]" – user2091683

+0

@ user2091683 - вам больше не нужно 'colnum'. 'zip (columns, rest.split (':'))' 'zips 'вместе, а словарь' doc' содержит всю запись. – eumiro

+0

Это мой новый код, Просьба открыть эту ссылку: (http://pastebin.com/qWPZsiyd) Эта ошибка происходит: Traceback (самый последний вызов последним): Файл «C: \ python27 \ yarab. py ", строка 26, в juza, chapter, verse, analysis = line.split ('', 3) ValueError: требуется больше, чем 1 значение для распаковки – user2091683