[英]Using re.sub to replace a
我有条短信。 我想删除某些单词和短语。
一句话是:我们在1990年代[/ b]年代住在那里。
我搜索它找到了吃 。 (=单词[0])
newline = re.sub('ate',newselectionString,line)
但是我只希望它自己找到ate ,而不是另一个词的一部分。
是否可以告诉re仅找到这3个字母?
文章的后面是:最好的事情是当我们吃冰淇淋时。
for line in lines:
for i in range(0, len(words)):
if words[i] in line:
print('Found ' + words[i])
newselectionString = selectionString.replace('GX', 'G' + str(startInt))
newline = re.sub(words[i], newselectionString, line)
newLines.append(newline)
startInt +=1
这有两种方法:
您想要的正则表达式为\\bate\\b
,或者该ate
应该出现在两个单词边界之间。 它会匹配We ate.
, I ate it.
,但不是We're late.
。
与普通的正则表达式非常相似,但是您可能希望控制句子中的其他单词。
word_fragments = re.split("\b", your_string)
print(' '.join([word for word in word_fragments if word != 'ate']))
将单词边界\\b
与str.format
一起str.format
。
例如:
re.sub(r"\b{}\b".format(words[i]), "Hello World", Text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.