从字符串中提取单词

时间:2020-05-19 20:01:19

标签: python

样本输入:

'note - Part model D3H6 with specifications X30G and Y2A is having features 12H89.'

预期输出:

['D3H6', 'X30G', 'Y2A', '12H89']

我的代码:

split_note = re.split(r'[.;,\s]\s*', note)
pattern = re.compile("^[a-zA-Z0-9]+$")  
#if pattern.match(ini_str):
for a in n2:
        if pattern.match(a):
            alphaList.append(a)

我需要从拆分字符串中提取所有字母数字单词并将其存储在列表中。

上面的代码无法提供预期的输出。

2 个答案:

答案 0 :(得分:1)

也许这可以解决问题:

import re 

# input string
stri = "Part model D3H6 with specifications X30 and Y2 is having features 12H89"
# words tokenization
split = re.findall("[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\'\w\-]+",stri)
# this statment returns words containing both numbers and letters
print([word for word in split if bool(re.match('^(?=.*[a-zA-Z])(?=.*[0-9])', word))])

#output: ['D3H6', 'X30', 'Y2', '12H89']

答案 1 :(得分:0)

^$用于一行的末尾,而不是一个单词。 除了示例单词外,不包含小写字母,为什么还要添加a-z

考虑您的示例,如果您需要获取一个同时包含至少一个字母和至少一个数字并且始终以数字结尾的单词,则为以下模式:

\b[0-9A-Z]+\d+\b

如果它可能以字母而不是数字结尾,但是仍然需要至少一位数字和一个字母,那么它将变得更加复杂:

\b[0-9A-Z]*\d|[A-Z][0-9A-Z]*\b

\b代表单词边界。