【问题标题】:How to search and replace with enclosed characters a text file?如何搜索并用封闭字符替换文本文件?
【发布时间】:2019-04-18 15:21:41
【问题描述】:

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

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))

【问题讨论】:

  • 每个单词都是以% 开头,后跟一个空格吗?
  • 是的@MattR,还有其他pythonic方法吗?

标签: python regex python-3.x io


【解决方案1】:

你可以使用

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)

【讨论】:

  • 我也有这种情况%hi_there我想把它们转换成[hi_there],这适用于这种情况吗?
  • @anon 查看我的回答:(\w+) - 第 1 组:任何 1 个或多个单词字符(字母、数字 _)。 会的。
猜你喜欢
  • 1970-01-01
  • 2016-09-22
  • 2020-05-12
  • 2012-12-27
  • 2020-05-12
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多