如何使用单词长度作为标记来拆分字符串

3

我正在使用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 Series并清除了标点符号,但未根据单词长度分割。

我希望看到类似以下示例的内容。

示例:

所以,

" and training requirements for selected salt applications"```

变成

['培训要求','选定盐应用程序']

并且,

"12月31日"

变成

['十二月']

并且,

"盐在过程热领域的紧急研究和应用的实验系统"

变成

['实验系统','盐','紧急研究','应用','过程热']

但是拆分没有捕获到小单词,我无法确定问题是正则表达式、re.split命令还是两者都有问题。

我可能可以采用暴力方法,但希望有一个优雅的解决方案。任何帮助都将不胜感激。


注意{1,3}是正确的,您需要使用原始字符串字面值。如果您需要在输出中保留这些单词,可以在模式周围使用捕获组,否则请删除()。尝试re.split(r"\s*\b\w{1,3}\b\s*", subArray) - Wiktor Stribiżew
1个回答

1
你可以使用

标签。

list(filter(None, re.split(r'\s*\b\w{1,3}\b\s*|[^\w\s]+', pubtitle.strip().lower())))

为了获得您想要的结果,请查看正则表达式演示r'\s*\b\w{1,3}\b\s*|[^\w\s]+ 正则表达式将小写字符串(使用 .lower())分成令牌,没有标点符号([^\w\s]+ 实现)和没有 1-3 个字符单词(\s*\b\w{1,3}\b\s* 实现),并且没有前导或尾随空格(由于 .strip())。 模式详细信息
  • \s* - 匹配0个或多个空格
  • \b - 单词边界
  • \w{1,3} - 匹配1到3个单词字符(如果不想匹配下划线,请使用[^\W_]+
  • \b - 单词边界
  • \s* - 匹配0个或多个空格
  • | - 或者
  • [^\w\s]+ - 匹配1个或多个非单词字符和空格字符。

请参阅Python演示

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接