Python 用特定条件替换使用正则表达式的word
只有在以下情况下,我如何使用python“re”模块将单词(即,Python 用特定条件替换使用正则表达式的word,python,regex,Python,Regex,只有在以下情况下,我如何使用python“re”模块将单词(即,'co')替换为空字符串,即给定文本中的'): 单词在课文的末尾,单词前有一个空格 这个单词不是课文中的最后一个单词,但在单词的开头有一个空格,然后在单词的结尾有另一个空格 即 # word is not the final word in the text but there's a space at beginning, and then another space at the end of the word txt =
'co'
)替换为空字符串,即给定文本中的'
):
- 单词在课文的末尾,单词前有一个空格
- 这个单词不是课文中的最后一个单词,但在单词的开头有一个空格,然后在单词的结尾有另一个空格
# word is not the final word in the text but there's a space at beginning, and then another space at the end of the word
txt = 'A co is mine'
txt_after_replace = 'A is mine'
txt = 'A column is mine'
txt_ater_replace = 'A column is mine'
# word is the end of the text and there's a space before the word
txt = 'my co'
txt_after_replace = 'my'
txt = 'my column'
txt_after_replace = 'my column'
如果我这样做:txt.replace('co','')
这两种情况将失败:txt='my column',txt\u ater\u replace='A column is my'
。因为它不会检查单词后面的文本结尾,也不会检查单词后面的文本中是否有空格
我认为re.sub模块会在这里进行救援,但我不确定如何进行
这应该适用于任何通用词,即在这种情况下,'co'
。您可以使用以下正则表达式来匹配这两个条件
正则表达式:(?:\sco\s |\sco$)
说明:
匹配前面和后面有空格的\sco\s
co
匹配\sco$
结尾处的空格co
import re
str = "coworker in my company are not so co operative. silly co"
res = re.sub(r'(?:\sco\s|\sco$)', ' ', str)
print(res)
结果:我公司的同事不是那么能干。愚蠢的
您可以使用正则表达式
\sco(?=$\s)
说明:
后跟space
,然后断言后跟co
的内容必须是co
或空格
文本结尾
import re
txt = 'A co is mine, A column is mine, my column, my co'
new_txt = re.sub('\sco(?=$|\s)', '', txt)
# 'A is mine, A column is mine, my column, my'
我认为你不能同时满足这两个标准。第一个正则表达式是
\b\w+$
(如果单词前有标点符号,则会稍微匹配),第二个正则表达式可以使用捕获组“(\w+).*$”
@Beefster谢谢你的帮助,根据我接受的答案,这是可能的。我说了你的意思是“要么”条件。@Beefster明白了,谢谢,不是更清楚的问题,我知道,为英语道歉…;-)或者更好的(\s?\bco\b\s?)
@sKwa在这种情况下似乎失败了:re.sub(“(\s?\bco\b\s?),“'my co sa')@sKwa:可选空间即使存在也会跳过。@Rahul lol“我公司的同事不太合作。愚蠢的合作”@Dnaiel,我在Rahul的feedle中使用,在feedle OèO中工作