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

时间:2017-04-25 10:42:35

标签: 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_string中找到的键的最低索引。

这是列名字典:

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

在上面的字典中,'status'4中的input_string索引编号最低。


同样,这里是价值字典:

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

如何清楚地区分列表中的值?

1 个答案:

答案 0 :(得分:2)

检查以下方法:

  • 根据英语nltk禁用词列表构建正则表达式以从结果中删除不相关的单词
  • 使用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'}
相关问题