[英]Python, Remove word start with specific character
如何在python中删除以特定字符开头的单词?
例如。
string = 'Hello all please help #me'
我想删除以#
开头的单词
我想要的结果是:
Hello all please help
>>> a = "Hello all please help #me "
>>> filter(lambda x:x[0]!='#', a.split())
['Hello', 'all', 'please', 'help']
你可以使用空格加入它:
>>> " ".join(filter(lambda x:x[0]!='#', a.split()))
'Hello all please help'
让我一步一步解释你:
>>> a = "Hello all please help #me "
>>> a.split() # split, splits the string on delimiter, by default its whitespace
['Hello', 'all', 'please', 'help', '#me']
>>> >>> filter(lambda x:x[0]!='#', a.split())
['Hello', 'all', 'please', 'help']
filter
仅返回条件为True的元素。
在这里使用split
一个问题是它删除了空格。 例如,
In [114]: 'a b \tc\nd'.split()
Out[114]: ['a', 'b', 'c', 'd']
所以用' '.join
再次将它重新连接起来改变原始字符串:
In [115]: ' '.join('a b \tc\nd'.split())
Out[115]: 'a b c d'
如果你想保留原始字符串并删除以#
开头的单词,那么你可以使用正则表达式:
In [119]: import re
In [120]: re.sub(r'(\s)#\w+', r'\1', 'Hello all please help #me but#notme')
Out[120]: 'Hello all please help but#notme'
说明 :
https://regex101.com有一个方便的工具,可以帮助您理解正则表达式。 例如, 这是对"(\\s)#\\w+"
含义的解释:
1st Capturing group (\s)
\s match any white space character [\r\n\t\f ]
# matches the character # literally
\w+ match any word character [a-zA-Z0-9_]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
由于这个正则表达式模式从匹配空格开始, ' #me'
'but#notme'
匹配,但'but#notme'
不匹配。
re.sub
, r'\\1'
的第二个参数是替换模式。 \\1
告诉re.sub
将匹配替换为第一个捕获组。 所以比赛' #me'
被替换为空格' '
。
使用最明显的解决方案:
txt = 'Hello all please help #me'
# better to not use 'string' as variable name
' '.join(word for word in txt.split(' ') if not word.startswith('#'))
注意,在这种情况下,使用带有显式空格的split(' ')
作为分隔符可能更好,这与更常见的无参数split()
相反。 这样您就不会丢失换行符或多个空格。
我会做这样的事情:
' '.join(word for word in "help #me please".split() if word[0]!='#')
作为unutbu的答案的补充,在句子的开头捕捉事件
> re.sub(r'(\s)#\w+', r'\1', '#Hello all please help #me but#notme')
'#Hello all please help but#notme'
> re.sub(r'(\s)#\w+', r'\1', '#Hello all please help #me but#notme')
'all please help but#notme'
没有足够的代表发表评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.