Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从子字符串列表中搜索列表中的子字符串_Python_List_Substring - Fatal编程技术网

Python-从子字符串列表中搜索列表中的子字符串

Python-从子字符串列表中搜索列表中的子字符串,python,list,substring,Python,List,Substring,尝试使用关键字列表按关键字搜索另一个字符串列表。有些格式有点奇怪 结果列表=['用户1\n出生日期','1990年1月11日','用户1年龄','29','用户1收入','60000', “用户2\n用户名”、“来宾用户2”、“用户2年龄”、“25”、“用户2收入”、“45000”] 关键词=['出生日期','年龄','收入','用户名'] 我尝试了以下代码: 最终dict={} 对于rangelenresults\u列表中的r: 对于关键字中的单词: 如果结果列表[r]中的关键词[words]

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

结果列表=['用户1\n出生日期','1990年1月11日','用户1年龄','29','用户1收入','60000', “用户2\n用户名”、“来宾用户2”、“用户2年龄”、“25”、“用户2收入”、“45000”] 关键词=['出生日期','年龄','收入','用户名'] 我尝试了以下代码:

最终dict={} 对于rangelenresults\u列表中的r: 对于关键字中的单词: 如果结果列表[r]中的关键词[words]: 关键词[字] 打印结果列表[r] r\u key\u idx=结果列表。索引结果列表[r] r_val_idx=r_key_idx+1 dictionary={results\u list[r\u key\u idx]:results\u list[r\u val\u idx]} 最终指令更新指令 这将生成一个

{'user 1 age':'29','user1 income':'60000','user 2 age':'25','user2 income':'45000'} *注意,在本例中,它查找子字符串。但在我的工作数据集中,它不是。在repl.it中对其进行了测试,结果成功了

它似乎没有抓住其中包含\n的。我不想只创建一堆不同的关键字,因为它经常根据表中的值进行更改,这是一个相当大的表,使用\n创建数百个不同的关键字似乎会弄巧成拙


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

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

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'] 


在比较之前,您需要清理字符串

还有一件事,如果您的结果列表在下一个索引上总是有一个键和它的值,那么您可以使用带有跳转参数的range方法

final_dict = {}
for i in range(0, len(results_list), 2):
    # This will change multiple spaces into 1 including \n
    key = " ".join(results_list[i].split())
    print(key)
    if [keyword for keyword in keywords if keyword in key]:
        final_dict[key] = results_list[i+1]