【问题标题】:how to match elements of two lists and access their indexes如何匹配两个列表的元素并访问它们的索引
【发布时间】:2018-02-03 11:44:23
【问题描述】:

我想匹配列表中的元素并将匹配后的下一个索引附加到数组列表中,但在我的代码中它给了我一个空数组。我不知道问题出在哪里。在我的代码中,结果也是一个数组,其中包含一个名为 '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.减少解释 2. 更少代码,更多示例 3. 一些输入和预期输出会有所帮助

标签: python arrays string list


【解决方案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,这将有助于理解

【讨论】:

    猜你喜欢
    • 2013-08-18
    • 2021-05-19
    • 1970-01-01
    • 2015-08-06
    • 2018-08-21
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多