繁体   English   中英

使用正则表达式删除单词中的空格 - 用于文本挖掘的预处理数据

[英]Deleting spaces within words with regex - pre-processing data for text mining

对于一个学校项目,我正在研究 Kaggle 上的 kickstarter 数据集; https://www.kaggle.com/kemical/kickstarter-projects

在“name”变量中,有几个标题之间有空格; 例如实例 373 “C R OSSTOWN”。

我整天都在研究一些正则表达式来重新划分多余的空格,并试图让它看起来像一个正常的单词。 虽然我认为这是一个更经常发生的问题,但大多数正则表达式内容是添加空格,或者添加双空格。 从来没有这个特定的任务。

我尝试了几种方法来描述需要删除的确切类型的空间,将字符挑出来作为一个组保留,并将它们用作替换字符串。 虽然它看起来应该可以工作,但我的数据没有改变。

  • 编写长正则表达式以识别写为空格+单个大写的单词(为此尝试了几个不同的)
  • r'\2\4' 指第二组和第四组(第一个和第二个字母字符)

 Names_fixed = [] for i in Name_New: Names_fixed.append(re.sub(r'(\s|^)([AZ])(\s)(AZ)\s/g', r'\2\4', i))

由于我对正则表达式还很陌生,因此向社区寻求帮助; 提前非常感谢。

如果您的目标只是从单词中删除空格,那么不确定您是否真的需要正则表达式。

您可以像这样使用简单的 replace() function:

x = "C R O S S T O W N"
x = x.replace(' ','')

你可以在你的列表上为所有这些词运行一个循环。

用这个:

re.sub(r'(?<![ \t])[A-Z](?:[ \t][A-Z])+(?![ \t])', lambda x: x.group().replace(' ','').replace('\t',''), i)

查找空格/制表符分隔的单词并从找到的文本中删除空格/制表符。

解释

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    [ \t]                    any character of: ' ', '\t' (tab)
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  [A-Z]                    any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (1 or more times
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    [ \t]                    any character of: ' ', '\t' (tab)
--------------------------------------------------------------------------------
    [A-Z]                    any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
  )+                       end of grouping
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [ \t]                    any character of: ' ', '\t' (tab)
--------------------------------------------------------------------------------
  )                        end of look-ahead

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM