首页 > 解决方案 > Python - 从子字符串列表中搜索列表中的子字符串

问题描述

尝试使用关键字列表通过关键字搜索另一个字符串列表。其中一些格式有点奇怪。

results_list = ['user 1 \n    date of birth', '11 Jan 1990','user 1 age', '29','user 1 income', '60 000',
'user 2 \n    username', 'guest_user2','user 2 age', '25','user 2 income', '45 000']
keywords = ['date of birth','age','income','username']

我试过这段代码:

final_dict = {}
for r in range(len(results_list)):
   for word in range(len(keywords)):
       if keywords[words] in results_list[r]:
           print(keywords[word])
           print(results_list[r])
           r_key_idx = results_list.index(results_list[r])
           r_val_idx = r_key_idx + 1
           dictionary = {results_list[r_key_idx]:results_list[r_val_idx]}
           final_dict.update(dictionary)

这导致输出字典

{'user 1 age':'29', 'user1 income':'60 000', 'user 2 age':'25', 'user2 income':'45 000'}

*注意,在此示例中,它会找到子字符串。但在我的工作数据集中,它没有。在 repl.it 中对其进行了测试,并且可以正常工作。

它似乎没有抓住其中的那些\n。我不想只制作一堆不同的关键字,因为它会根据表中的值经常变化,而且它是一个相当大的表,并且制作数百个不同的关键字\n似乎是弄巧成拙。

另外,请注意这些示例与我的实际数据集不同(实际数据集在 之后大约有 12 个空格\n,但不确定这是否会改变任何东西)。

标签: pythonlistsubstring

解决方案


尝试先清理您的数据列表,然后运行您的代码。像下面这样清理您的数据。您的关键字应该在此之后匹配。

results_list = ['user 1 \n    date of birth', '11 Jan 1990','user 1 age', '29','user 1 income', '60 000',
'user 2 \n    username', 'guest_user2','user 2 age', '25','user 2 income', '45 000']

for index, res in enumerate(results_list):
    if '\n' in res:
        new_res = res.split('\n')
        #remove empty space to the left
        new_res[1] = new_res[1].lstrip(" ")
        results_list[index] = "".join(new_res)

print(results_list)#place your code after this line


#['user 1 date of birth', '11 Jan 1990', 'user 1 age', '29', 'user 1 income', '60 000', 'user 2 username', 'guest_user2', 'user 2 age', '25', 'user 2 income', '45 000'] 


推荐阅读