简体   繁体   English

如何在关键字之前获取数字?

[英]How to get numbers just before key words?

I have the following code:我有以下代码:

result = dict()
for i in ['ABC', 'DEF']:
    result[i] = re.findall('{0}(.*?)(\d+\.*\d*-*\d+\.*\d*.*?)'.format(i), 'ABC costs 40000-50000 dollars; the price of car DEF is 45600-80000, HIJ only needs 30000USD')

It returns:它返回:

{'ABC': [(' costs ', '40000-50000')], 'DEF': [(' is ', '45600-80000')]}

However, I want the following:但是,我想要以下内容:

{'ABC': ['40000-50000'], 'DEF': ['45600-80000'], 'OTHERS' : ['30000']}

Note that keywords not equal ABC and DEF are regarded as OTHERS .请注意,不等于ABCDEF关键字被视为OTHERS How to solve the problem?如何解决问题?

This approach does a top line find all to get all three letter abbreviations along with numeric values/ranges.这种方法做一个顶线 find all 来获得所有三个字母的缩写以及数值/范围。 Then it uses a list comprehension combined with zip and dict to generate the dictionary you want.然后它使用列表理解结合zipdict来生成你想要的字典。

inp = "ABC costs 40000-50000 dollars; the price of car DEF is 45600-80000, HIJ only needs 30000USD"
matches = re.findall(r'\b[A-Z]{3}\b|\d+(?:-\d+)?', inp)
print(matches)
map_out = dict(zip([matches[i] for i in range(0, len(matches), 2)],
                   [matches[i] for i in range(1, len(matches), 2)]))
print(map_out)

This prints:这打印:

['ABC', '40000-50000', 'DEF', '45600-80000', 'HIJ', '30000']
{'HIJ': '30000', 'ABC': '40000-50000', 'DEF': '45600-80000'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在wordnet中获得相似的单词(不仅仅是同义词)? - How to get similar words in wordnet (not just synonyms)? 如何从 python 中的数字和单词的原始列表中创建仅包含数字和单词/短语的新列表? - How to create a new list with just numbers and words/phrases from a original list with both numbers and words in python? 关键字搜索仅在文件的一列中,并在关键字前后保留2个单词 - Key word search just in one column of the file and keeping 2 words before and after key word 我如何在Python中的关键搜索词之前和之后显示2个单词 - How I display 2 words before and after a key search word in Python 如何获取键前和键后的值 - How to get the values before a key and after a key 如何仅用一个键来获取所有数据存储结果? - how to get all the datastore results just with a key? 获取字符串中数字的索引并提取数字前后的单词(不同语言) - Get the indices of numbers in a string and extract words before and after the number (in different languages) 最大(*args,关键=...)。 如何修改键以获取某些值? - max(*args, key = ... ). How to modify key to get just certain values? 如何获得特定令牌前后的单词? - How can I get words after and before a specific token? 如何让 python 搜索字符串中的整数,而不仅仅是数字 - How to get python to search for whole numbers in a string-not just digits
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM