我有一个文本如下。你知道吗
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
我想把它转换成小写,除了有_ABB
的单词。你知道吗
所以,我的输出应该如下所示。你知道吗
mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday"
我现在的代码如下。你知道吗
splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)
然而,我想知道是否有任何简单的方法可以做到这一点,可能在一行?你知道吗
您可以使用一行代码将字符串拆分为单词,用
str.endswith()
检查单词,然后将单词重新连接在一起:当然,如果
'_ABB'
实际上可以出现在单词的任何地方,而不仅仅是在词尾,那么使用in
运算符而不是str.endswith()
。你知道吗下面是另一个可能的(不优雅的)一行:
输出:
注意:这假设您的文本将只按空格分隔单词,因此
split()
在这里就足够了。如果文本中包含",!."
等标点符号,则需要使用regex来拆分单词。你知道吗扩展的正则表达式方法:
输出:
详情:
\b
-词边界(?!_ABB)
-lookahead否定断言,确保给定的模式不匹配\S
-非空白字符\b((?!_ABB)\S)+\b
-整个模式匹配不包含子串的单词_ABB
相关问题 更多 >
编程相关推荐