python - 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
,但不确定这是否会改变任何东西)。
解决方案
尝试先清理您的数据列表,然后运行您的代码。像下面这样清理您的数据。您的关键字应该在此之后匹配。
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']
推荐阅读
- sql - 在 Bigquery 中使用 REGEXP_EXTRACT 查找破折号之间的字符串
- unity3d - 缩放水平布局组的子布局元素,同时保持它们的纵横比
- c++ - std::ifstream::open 不一致失败
- python - 优化一个参数,使输出位于两点之间
- python - 返回一个包含每家公司最高销售额的完整行的 python DataFrame
- azure - k8s 无法访问数据库
- flutter - 无法将 google_sign_in 添加到 Flutter 项目,包需要旧版本的 Flutter SDK?
- c# - 例外:当用户输入 C:\Name 时,不支持给定的路径格式
- c# - 在 Windows 或 linux 上运行时如何设置 nlog.config 以使用正确的目录分隔符
- ios - 如何将下载的数据从 Firestore 转换为数组并将其分配给我的表格视图?