对于一个学校项目,我正在研究kickstarter on Kaggle;https://www.kaggle.com/kemical/kickstarter-projects
在"name“变量中,有几个标题在它们之间有空格;例如,实例373 "C、R、O、S、T、O、W、N”。
我一整天都在做一些正则表达式( regex ),以re.sub额外的空格,并试图使它看起来像一个正常的词。虽然我认为这是一个更经常发生的问题,但大多数regex内容都是添加空格,或者添加双空格。从来没有这样具体的任务。
我尝试了几种方法来描述需要删除的确切空间类型,选择要作为一个组保存的字符,并使用它们作为替换字符串。虽然它看起来应该正常工作,但我的数据并没有改变。
Names_fixed = []
for i in Name_New:
Names_fixed.append(re.sub(r'(\s|^)([A-Z])(\s)(A-Z)\s/g', r'\2\4', i))
因为我对regex还是很陌生的,所以我求助于社区,提前感谢大家。
发布于 2021-05-15 20:55:42
用这个:
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发布于 2021-05-15 16:32:16
如果您的目标只是从单词中删除空格,请不要确定您是否真的需要regex。
您可以使用以下简单的替换()函数:
x = "C R O S S T O W N"
x = x.replace(' ','')您可以在列表上对所有这样的单词运行循环。
https://stackoverflow.com/questions/67548815
复制相似问题