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)
我需要从拆分字符串中提取所有字母数字单词并将它们存储在列表中。
上面的代码无法给出预期的输出。
解决方案
也许这可以解决问题:
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']
推荐阅读
- c# - 是否可以在数组中获取 null 而不是超出范围异常?
- macos - 如何运行完整的 Haskell 程序
- kubernetes - Kubernetes ingress-nginx LoadBalancer 指向云桶
- python - 一种无需重写即可更新 csv 文件的方法
- java - 如何创建一个返回包含另一个数组重复值的新数组的函数
- python - 如何使用 python sqlite 输出数据?
- javascript - 如何创建带有音频 blob 的音频文件?
- data-structures - 键范围大小 < 10,哈希函数的每个数字 ∈ [0, 3]
- r - 如何在 R 中应用 Cochran-Armitage 趋势检验
- c++ - 如何避免 Process2 一直等待 Process1 释放 named_mutex 的情况