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

标签 python regex python-3.x io

给定一个纺织品,我如何替换 [] 的所有以 % 开头的标记。例如在以下文本文件中:

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

如何用 [] 将所有带有 % 的字符括起来:

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

我尝试先过滤标记然后替换它们,但也许有更 pythonic 的方法:

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)

参见 regex demo

详情

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

Python demo :

import re

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

关于python - 如何搜索并用封闭的字符替换文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53320881/

相关文章:

java - 我的 String 和 StringBuilder 未在控制台中显示输出

python - 字符串列表到整数数组

python - Django:get() 返回了多个项目——它返回了 3 个

Python3错误: AttributeError: module 'urllib' has no attribute 'request'

python - 在 python 3.6 中绘制颜色条图例很困难

regex - 在正则表达式中第一次出现时停止

php - 使用正则表达式查找匹配的括号

python - 如何设计Python过滤器函数以便能够使用加法属性进行排序?

python - 在元组中搜索集合

python - Python 3.x 可以强制方法参数是特定的类实例/对象吗? (阿拉 PHP)