Python中的“列表索引超出范围”

0 投票
2 回答
546 浏览
提问于 2025-04-17 16:38

我有一段用Python写的代码,用来给一个包含阿拉伯语单词的文本文件建立索引。我在一个英文文本上测试过这段代码,运行得很好,但在阿拉伯语文本上测试时却出现了错误。

注意:这个文本文件是用Unicode编码保存的,而不是ANSI编码。

这是我的代码:

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

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

schema = fields.Schema(juza=fields.NUMERIC,
                       chapter=fields.NUMERIC,
                       verse=fields.NUMERIC,
                       voc=fields.TEXT)

# Create the Whoosh index
indexname = "indexdir"
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:
  with open("h.txt", 'r') as txtfile:
    lines=txtfile.readlines()

    # Read each row in the file
    for i in lines:

      # Create a dictionary to hold the document values for this row
      doc = {}
      thisline=i.split()
      u=0

      # Read the values for the row enumerated like
      # (0, "juza"), (1, "chapter"), etc.
      for w in thisline: 
        # Get the field name from the "columns" list
          fieldname = columns[u]
          u+=1
          #if isinstance(w, basestring):
          #     w = unicode(w)
          doc[fieldname] = w
      # Pass the dictionary to the add_document method
      writer.add_document(**doc)
with ix.searcher() as searcher:
    query = QueryParser("voc", ix.schema).parse(u"بسم")
    results = searcher.search(query)
    print(len(results))
    print(results[1]) 

然后出现的错误是:

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

这是文件的一个示例:

1   1   1   كتاب
1   1   2   قرأ
1   1   3   لعب
1   1   4   كتاب

2 个回答

0

你在脚本里漏掉了Unicode的头部信息。第一行应该是:

编码:utf-8

另外,要用Unicode编码打开一个文件,可以使用:

import codecs 
with codecs.open("s.txt",encoding='utf-8') as txtfile:
0

虽然我看不出有什么明显的问题,但我建议你要考虑到可能出现的错误。确保你能处理任何情况下,split() 函数返回的元素数量超过预期的情况,并及时处理这些情况(比如打印错误信息并结束程序)。看起来你可能在处理格式不正确的数据。

撰写回答