Python 如何从字符串创建有意义的列-值对列表?
我试图使用Python字典从输入字符串中对列和值(column=value)进行有意义的分类Python 如何从字符串创建有意义的列-值对列表?,python,string,nlp,semantics,Python,String,Nlp,Semantics,我试图使用Python字典从输入字符串中对列和值(column=value)进行有意义的分类 input_string = "the status is processing and product subtypes are HL year 30 ARM and applicant name is Ryan" 我已经创建了键值对字典。在第一个场景中,键是列名。该值表示在input\u string中找到的键的最低索引 这是列名字典: dict_columns = {'status': 4,
input_string = "the status is processing and product subtypes are HL year 30 ARM and applicant name is Ryan"
我已经创建了键值对字典。在第一个场景中,键是列名。该值表示在input\u string
中找到的键的最低索引
这是列名字典: dict_columns = {'status': 4, 'product subtypes': 29, 'applicant name': 69}
在上面的字典中,'status'
在输入字符串中具有最低的索引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']
如何清楚区分列表中的值?检查以下方法:
- 构建正则表达式,根据英语nltk停止词列表从结果中删除不相关的词
- 使用
dict\u列
键构建正则表达式以拆分文本
- 拆分后,将结果列表压缩为元组列表
- 从值中删除不相关的单词并去掉空白
以下是我迄今为止的代码:
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'}
在处理原始数据(非结构化)时,我建议您使用regex
,请在此添加更多输入和所需输出的示例。想法:re.split
,使用r'\b(?:status | product subtypes | applicator name)\b'
,和。丢弃空元素。要知道它是哪种类型的信息,可以使用与上面相同的模式进行拆分,但要删除?:
。然后,您可以检查每个奇数列的值和偶数列的键。非常感谢。我真的很感激你的帮助。它现在运转良好。