python中的二维数组索引
我想计算一个数组中的每个单词在文本文件中出现的次数。如果在shell中编写print语句,我将获得输出。但当我把它作为文件运行时就不是了。我遇到了一个错误“indexer-ror:list-index-out-range”。我是python初学者,请帮助我解决这个问题python中的二维数组索引,python,arrays,string,for-loop,indexing,Python,Arrays,String,For Loop,Indexing,我想计算一个数组中的每个单词在文本文件中出现的次数。如果在shell中编写print语句,我将获得输出。但当我把它作为文件运行时就不是了。我遇到了一个错误“indexer-ror:list-index-out-range”。我是python初学者,请帮助我解决这个问题 from collections import Counter from array import * import string cnt=Counter() file = open('output.txt', 'r') word
from collections import Counter
from array import *
import string
cnt=Counter()
file = open('output.txt', 'r')
word =[ ]
c=[ ]
count =0
first_word =[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
word_count = [ ]
new_array =['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT',
'POS','PRP','PRP$','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBZ','WDT','WP$','WP','WRB']
for line in file:
words = line.split()
word.append(words)
for i in range(0,30):
for j in range(0,33):
if(new_array[j] in word[i][0]):
first_word[j]+=1
else:
continue
print first_word
当您不想迭代
列表时,不要对范围使用显式值,而是使用正在迭代的列表长度。这样就不会出现索引错误。因此,替换:
for i in range(0,30):
for j in range(0,33):
与:
我想它会解决这个问题。此外,当您必须使用类似的值初始化列表时,例如:
first_word =[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
python中有一种简单的方法可以实现这一点:
>>> first_word = [0]*33
>>> first_word
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
我认为下面的代码应该可以得到您需要的结果:
wordsFromFile = []
f = open("output.txt", 'r')
for each_line in f:
wordsFromFile.extend(each_line.strip().split(" "))
f.close()
print wordsFromFile
new_array = ['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT',
'POS','PRP','PRP$','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBZ','WDT','WP$','WP','WRB']
first_word = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for eachWordFromFile in wordsFromFile:
if eachWordFromFile in new_array:
first_word[new_array.index(eachWordFromFile)] += 1
#output results:
for i in range(0,33):
print str(new_array[i]) + ": " + str(first_word[i])
显示您的output.txt
。我明确地设置了范围,但仍然显示相同的错误
wordsFromFile = []
f = open("output.txt", 'r')
for each_line in f:
wordsFromFile.extend(each_line.strip().split(" "))
f.close()
print wordsFromFile
new_array = ['CC','CD','DT','EX','FW','IN','JJ','JJR','JJS','LS','MD','NN','NNS','NNP','NNPS','PDT',
'POS','PRP','PRP$','RB','RBR','RBS','RP','SYM','TO','UH','VB','VBD','VBZ','WDT','WP$','WP','WRB']
first_word = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for eachWordFromFile in wordsFromFile:
if eachWordFromFile in new_array:
first_word[new_array.index(eachWordFromFile)] += 1
#output results:
for i in range(0,33):
print str(new_array[i]) + ": " + str(first_word[i])