简体   繁体   English

替换文本中的字符串并忽略某些部分

[英]Replacing strings in a text and ignoring certain parts

I found many programs online to replace text in a string or file with words prescribed in a dictionary. 我在网上发现了许多程序,可以用字典中规定的单词替换字符串或文件中的文本。 For example, https://www.daniweb.com/programming/software-development/code/216636/multiple-word-replace-in-text-python 例如, https://www.daniweb.com/programming/software-development/code/216636/multiple-word-replace-in-text-python

But I was wondering how to get the program to ignore certain parts of the text. 但是我想知道如何让程序忽略文本的某些部分。 For instance, I would like it to ignore parts that are ensconced within say % signs (%Please ignore this%). 例如,我希望它忽略包含在%符号之内的部分(%请忽略此%)。 Better still, how do I get it to ignore the text within but remove the % sign at the end of the run. 更好的是,如何让它忽略其中的文本,但在运行结束时删除%符号。

Thank you. 谢谢。

This could very easily be done with regular expressions, although they may not be supported by any online programs you find. 尽管您可能找不到任何在线程序来支持正则表达式,但这很容易做到。 You will probably need to write something yourself and then use regex as your dict's search key's. 您可能需要自己编写一些内容,然后使用正则表达式作为dict的搜索关键字。

Good place to start playing around with regex is: http://regexr.com 开始使用regex的好地方是: http : //regexr.com

Well in the replacing dictionary just have any word you want to be ignored such as teh be replaced with the but %teh% be replaced with teh . 那么在更换字典只是有你想要的任何单词被忽略,如teh被替换the ,但%teh%被替换teh For the program in the link you could have 对于链接中的程序,您可能有

wordDic = {
    'booster': 'rooster',
    '%booster%': 'booster'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM