删除非字母字符,转换为小写,并删除小于3个字母的单词列表

问题描述 投票:0回答:2

我正在使用Python 2.7,我想知道我是否可以使用一行代码同时执行许多操作。

我目前有什么:

csvarticles = [['[Beta-blockers]', 'Magic!', '1980', 'Presse medicale'],['Hypertension in the pregnant woman].', '', '2010', 'Medical'],['Arterial hypertension.', '', '1920', 'La Nouvelle']]    
output =  [[re.sub("[^ '\w]"," ",x).strip().lower() for x in y] for y in csvarticles]
output = [[re.sub(r'\b\w{,3}\b','',x) for x in y] for y in output]
>>> [['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension   pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', ' nouvelle']]

这是我想要的输出,但有额外的空格。我并不担心额外的空间(除非它是一个简单的修复)。有什么方法可以将这两个单线组合起来吗?

我尝试过的:

output =  [[re.sub("[^ '\w{,3}]"," ",x).strip().lower() for x in y] for y in csvarticles]
>>> [['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension in the pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', 'la nouvelle']]

output =  [[re.sub("[r '\b\w{,3}\b]"," ",x).strip().lower() for x in y] for y in csvarticles]
>>> [['[    -        ]', '!', '', ''], ['].', '', '', ''], ['.', '', '', '']]

感谢@'rahlf23'和@'Jean-FrançoisFabre'解决我的第一个问题。我已经阅读了正则表达式的文档,我无法理解它。

python regex python-2.7
2个回答
1
投票

如果您将第二个正则表达式更改为\b\w{1,3}\s,则不会有额外的空格

output = [[re.sub(r'\b\w{1,3} ', '', re.sub("[^ '\w]", ' ', item)).strip().lower() for item in row] for row in csvarticles]

输出:

[['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', 'nouvelle']]

1
投票

你可以试试这个:

import re
csvarticles = [['[Beta-blockers]', 'Magic!', '1980', 'Presse medicale'],['Hypertension in the pregnant woman].', '', '2010', 'Medical'],['Arterial hypertension.', '', '1920', 'La Nouvelle']]    
new_data = [[re.sub(r'^\s+|\s+$', '', re.sub(r'\W+|\b\w{,3}\b', ' ', x)).lower() for x in i] for i in csvarticles]

输出:

[['beta blockers', 'magic', '1980', 'presse medicale'], ['hypertension     pregnant woman', '', '2010', 'medical'], ['arterial hypertension', '', '1920', 'nouvelle']]
© www.soinside.com 2019 - 2024. All rights reserved.