-1

私はこれをやっています:

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    allValues.append(line[theColumn-1])
  return list(set(allValues))

私は string index out of rangeこのラインに乗っています:

allValues.append(line[theColumn-1])

誰かが私が間違っていることを知っていますか?

必要に応じて、完全なコードを次に示します。

import hashlib

def doStuff():
  createFiles('together.csv')

def readFile(fileName):
  a=open(fileName)
  fileContents=a.read()
  a.close()
  return fileContents

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    allValues.append(line[theColumn-1])
  return list(set(allValues))

def createFiles(inputFile):
  inputFileText=readFile(inputFile)
  b = inputFileText.split('\n')
  r = readFile('header.txt')
  DISTINCTCOLUMN=12
  dValues = GetDistinctValues(inputFileText,DISTINCTCOLUMN)

  for uniqueValue in dValues:
    theHash=hashlib.sha224(uniqueValue).hexdigest()
    for x in b:
      if x[DISTINCTCOLUMN]==uniqueValue:
        x = x.replace(', ',',').decode('latin-1','ignore')
        y = x.split(',')
        if len(y) < 3:
          break
        elif len(y) > 3:
          desc = ' '.join(y[3:])
        else:
          desc = 'No description'
        # Replacing non-XML-allowed characters here (add more if needed)
        y[2] = y[2].replace('&','&amp;')

        desc = desc.replace('&','&amp;')

        r += '\n<Placemark><name>'+y[2].encode('utf-8','xmlcharrefreplace')+'</name>' \
          '\n<description>'+desc.encode('utf-8','xmlcharrefreplace')+'</description>\n' \
          '<Point><coordinates>'+y[0]+','+y[1]+'</coordinates></Point>\n</Placemark>'
    r += readFile('footer.txt')
    f = open(theHash,'w')
    f.write(r)
    f.close()
4

3 に答える 3

3

エラーの原因ではありません。長さが足りないappend()ためです。lineたぶんあなたのファイルの最後に空の行があります。あなたは試すことができます

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
    if line:
      allValues.append(line[theColumn-1])
  return list(set(allValues))

それ以外の場合、例外ハンドラーは何が問題になっているのかを見つけるのに役立ちます

def GetDistinctValues(theFile, theColumn):
  lines=theFile.split('\n')
  allValues=[]
  for line in lines:
     try:
        allValues.append(line[theColumn-1])
     except IndexError:
        print "line: %r"%line
  return list(set(allValues))
于 2012-08-27T06:33:43.837 に答える
3

これはline、コードが想定しているほど多くの要素がないために発生しています。次のことを試してください。

for line in lines:
    if len(line) < theColumn:
        print "This line doesn't have enough elements:\n" + line
    else:
        allValues.append(line[theColumn-1])
return list(set(allValues))

これにより、ヒントが得られます。これは、リストの範囲外の要素、つまり存在しない要素にアクセスしようとしたときに予想されるタイプのエラーです。

于 2012-08-27T06:32:40.247 に答える
2
line[theColumn-1])

もちろん、これにより、string(line)が短絡され、次に'theColumn'が短絡された場合に、前述のエラーが発生します。他に何を期待しますか?

于 2012-08-27T06:29:34.550 に答える