我正在使用 Python 3 准备包含文档标题的字符串,用作美国专利网站中的搜索词。
1)保留长短语是有好处的,但是
2) 当搜索包含许多长度不超过 3 个字符的词时,搜索效果不佳,因此我需要消除它们。
我已经尝试使用正则表达式“\b\w[1:3}\b *”来分割一到三个字母的单词,有或没有尾随空格,但没有成功。但是,我不是正则表达式方面的专家。
for pubtitle in df_tpdownloads['PublicationTitleSplit']:
pubtitle = pubtitle.lower() # make lower case
pubtitle = re.split("[?:.,;\"\'\-()]+", pubtitle) # tokenize and remove punctuation
#print(pubtitle)
for subArray in pubtitle:
print(subArray)
subArray = subArray.strip()
subArray = re.split("(\b\w{1:3}\b) *", subArray) # split on words that are < 4 letters
print(subArray)
上面的代码遍历了一个 pandas 系列并清除了标点符号,但未能按字长进行拆分。
我希望看到类似下面示例的内容。
例子:
所以,
" and training requirements for selected salt applications"```
成为
['培训要求', '选定的盐应用程序']
。
还有,
“12 月 31 日”
成为
['十二月']
。
还有,
“盐在涌现研究中的实验系统及其在过程热中的应用”
成为
['实验系统', '盐', '新兴研究', '应用', '过程热']
。
但是拆分并没有捕获小词,我无法判断问题出在正则表达式、re.split 命令还是两者。
我可能会采用蛮力方法,但想要一个优雅的解决方案。 任何帮助将不胜感激。
最佳答案
你可以使用
list(filter(None, re.split(r'\s*\b\w{1,3}\b\s*|[^\w\s]+', pubtitle.strip().lower())))
获得你想要的结果。查看regex demo .
r'\s*\b\w{1,3}\b\s*|[^\w\s]+'
正则表达式拆分小写字母(使用 . lower()
) 没有前导和尾随空格的字符串(由于 .strip()
)转换为没有标点符号的标记 ([^\w\s]+
这样做)并且没有 1-3 个字的字符字(\s*\b\w{1,3}\b\s*
这样做)。
图案细节
\s*
- 0+ 个空格\b
- 单词边界\w{1,3}
- 1、2 或 3 个字符(如果您不想匹配_
,请使用[^\W_] +
)\b
- 单词边界\s*
- 0+ 空格|
- 或者[^\w\s]+
- 除了单词和空白字符之外的 1 个或多个字符。
参见 Python demo :
import re
df_tpdownloads = [" and training requirements for selected salt applications",
"december 31",
"experimental system for salt in an emergence research and applications in process heat"]
#for pubtitle in df_tpdownloads['PublicationTitleSplit']:
for pubtitle in df_tpdownloads:
result = list(filter(None, re.split(r'\s*\b\w{1,3}\b\s*|[^\w\s]+', pubtitle.strip().lower())))
print(result)
输出:
['training requirements', 'selected salt applications']
['december']
['experimental system', 'salt', 'emergence research', 'applications', 'process heat']
关于python - 如何使用字长作为标记来拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426547/