如何从字符串创建有意义的列-值对列表?

2024-10-02 22:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python字典对输入字符串中的列和值(column=value)进行有意义的分类。你知道吗

input_string = "the status is processing and product subtypes are HL year 30 ARM and applicant name is Ryan"

我已经创建了键值对字典。在第一个场景中,是列名。表示在input_string中找到的键的最低索引。你知道吗

这是列名词典:

 dict_columns = {'status': 4, 'product subtypes': 29, 'applicant name': 69}

在上面的字典中,'status'input_string中有最低的4索引。你知道吗


类似地,这里是值字典:

dict_values = {'processing': 14, 'hl': 50, 'year': 53, '30': 58, 'arm': 61, 'ryan': 87}

问题是:
如何获得预期输出:

list_parsed_values = ['processing', 'hl year 30 arm', 'ryan']

和相应的列列表(可选):

list_parsed_columns = ['status', 'product subtypes', 'applicant name']

如何清晰区分列表中的值?


Tags: columnsandnameinputstring字典isstatus
1条回答
网友
1楼 · 发布于 2024-10-02 22:31:54

检查以下方法:

  • 根据英语nltk非索引词列表构建regex,从结果中删除不相关的词
  • 使用dict_columns键构建正则表达式以拆分文本
  • 拆分后,将结果列表压缩为元组列表
  • 从值中删除不相关的词并去掉空白

以下是我迄今为止的代码:

import nltk, re
s = "the status is processing and product subtypes are HL year 30 ARM and applicant name is Ryan"
dict_columns = {'status': 4, 'product subtypes': 29, 'applicant name': 69}
dict_values = {'processing': 14, 'hl': 50, 'year': 53, '30': 58, 'arm': 61, 'ryan': 87}
# Build the regex to remove irrelevant words from the results
rx_stopwords = r"\b(?:{})\b".format("|".join([x for x in nltk.corpus.stopwords.words("English")]))
# Build the regex to split the text with using the dict_columns keys
rx_split = r"\b({})\b".format("|".join([x for x in dict_columns]))
chunks = re.split(rx_split, s)
# After splitting, zip the resulting list into a tuple list
it = iter(chunks[1:])
lst = list(zip(it, it))
# Remove the irrelevant words from the values and trim them (this can be further enhanced
res = [(x, re.sub(rx_stopwords, "", y).strip()) for x, y in lst]
# =>
#   [('status', 'processing'), ('product subtypes', 'HL year 30 ARM'), ('applicant name', 'Ryan')]
# It can be cast to a dictionary
dict(res)
# => 
#   {'product subtypes': 'HL year 30 ARM', 'status': 'processing', 'applicant name': 'Ryan'}

相关问题 更多 >