繁体   English   中英

如何搜索并用封闭的字符替换文本文件?

[英]How to search and replace with enclosed characters a text file?

给定一种纺织品,我该如何替换[]开头具有%所有令牌。 例如在以下文本文件中:

Hi how are you? 
I %am %fine.
Thanks %and %you

如何用[]将所有字符括在%

Hi how are you? 
I [am] [fine].
Thanks [and] [you]

我尝试先过滤令牌,然后替换它们,但也许有一种更Python化的方式:

with open('../file') as f:
    s = str(f.readlines())
    a_list = re.sub(r'(?<=\W)[$]\S*', s.replace('.',''))
    a_list= set(a_list)
    print(list(a_list))

您可以使用

re.sub(r'\B%(\w+)', r'[\1]', s)

正则表达式演示

细节

  • \\B非单词边界,当前位置的左边必须有字符串开头或非单词char
  • % -一%字符
  • (\\w+) -第1组:任意1个或多个单词字符(字母,数字或_ )。 如有必要,请替换为(\\S+)以匹配1个或多个非空格字符,但请注意\\S也匹配标点符号。

Python演示

import re

s = "Hi how are you? \nI %am %fine.\nThanks %and %you"
result = re.sub(r"\B%(\w+)", r"[\1]", s)
print(result)

暂无
暂无

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

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