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

2024-09-28 19:05:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.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-franois Fabre'解决了我的第一个问题。我已经通读了regex的文档,我就是想不起来。你知道吗


Tags: theinreforoutputmagiclowerbeta
2条回答

如果将第二个正则表达式更改为^{},则不需要额外的空格

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

你可以试试这个:

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

相关问题 更多 >