如何匹配两个列表的元素并访问它们的索引

时间:2017-08-25 12:11:33

标签: python arrays string list

我想匹配列表中的元素并在匹配后将下一个索引追加到数组列表中但在我的代码中它给了我一个空数组。我不知道问题出在哪里。在我的代码中,结果也是一个包含一个名为'hilalitag.txt'的文件的数组,这个文件被分成单词。但为了简单起见,我将结果称为一个数值很少的数组。我想将结果元素与单词元素匹配,如果在单词中找到匹配,那么我需要在名为arr []的数组中追加匹配后的单词的下一个索引。

sample_text='ahmedrazatg.txt'
lemmatizer=WordNetLemmatizer()
file = open(sample_text,'r')
arr=[]
result=[]
for line in file.readlines():
   words=re.split(' |/|:|;|,|-RRB-|-LRB-|!|\*|\*\*|``',line) #removing punctuations from file
   words=[line.replace(".","") for line in words] #removing full stop from file        
   i=4
   while i<len(words):            # this loop store words of a file in an array
      l=lemmatizer.lemmatize(words[i]) #array of words is lematized here
      i += 1
      result=['Alphabets','reveals','help','opinions','Allah'] 
      j=4
      for j in words:
         if j in result:
            arr.append(j+1)
      print(arr)

1 个答案:

答案 0 :(得分:1)

很可能你需要这个:

arr = []
result=['Alphabets','reveals','help','opinions','Allah'] 
words=['Alphabets',"1",'reveals',"2",'help',"3",'opinions',"4",'Allah',"5"] 

for j in range(0, len(words)):
 if words[j] in result:
    arr.append(words[j+1])
print(arr)

如果不是,请添加一些较短的代码和 expected output ,这将有助于理解

相关问题