[英]How to search and replace with enclosed characters a text file?
Given a textile how can I replace all the tokens that have %
at the beginning for []
. 给定一种纺织品,我该如何替换
[]
开头具有%
所有令牌。 For instance in the following text file: 例如在以下文本文件中:
Hi how are you?
I %am %fine.
Thanks %and %you
How can I enclose all the characters with %
with []
: 如何用
[]
将所有字符括在%
:
Hi how are you?
I [am] [fine].
Thanks [and] [you]
I tried to first filter the tokens and then replace them but maybe there is a more pythonic way: 我尝试先过滤令牌,然后替换它们,但也许有一种更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))
You may use 您可以使用
re.sub(r'\B%(\w+)', r'[\1]', s)
See the regex demo 见正则表达式演示
Details 细节
\\B
- a non-word boundary, there must be start of string or a non-word char immediately to the left of the current location \\B
非单词边界,当前位置的左边必须有字符串开头或非单词char %
- a %
char %
-一%
字符 (\\w+)
- Group 1: any 1 or more word chars (letters, digits or _
). (\\w+)
-第1组:任意1个或多个单词字符(字母,数字或_
)。 Replace with (\\S+)
to match 1 or more non-whitespace chars if necessary, but note \\S
also matches punctuation. (\\S+)
以匹配1个或多个非空格字符,但请注意\\S
也匹配标点符号。 Python demo : 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.