Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用特定条件替换使用正则表达式的word_Python_Regex - Fatal编程技术网

Python 用特定条件替换使用正则表达式的word

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 =

只有在以下情况下,我如何使用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 = '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
    结尾处的空格

在python中:

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
    的内容必须是
    空格
    文本结尾
python代码

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中工作