我有以下 sed 脚本:
cat foo.txt | sed -e "s/.*\[\([^]]*\)\].*/\1/g" -e "s/ //g" -e "s/'//g"
可以翻译成三种表达方式:
- 捕获之间的所有文本
[...]
- 删除空格
- 删除所有单引号
在 python 中对文本文件执行类似操作的巧妙方法是什么?
你可以用正则表达式re.sub()
(
import re
s = "some string ['foo'] [b a r] [baz] [] extra stuff"
pat0 = re.compile(r'\[([^]]*)\]')
lst0 = pat0.findall(s)
lst1 = [s.replace(' ', '') for s in lst0]
lst2 = [s.replace("'", '') for s in lst1]
print(lst2) # prints: ['foo', 'bar', 'baz', '']
另一种解决方案:
import re
regex = re.compile("\[([^\]]+)\]")
out = list()
for line in open("foo.txt", "rt"):
out.extend(i.translate(None, "' ") for i in re.findall(regex, line.strip()))
print out
import re
with open('foo.txt', 'r') as f:
read_data = f.readlines()
out_data = []
for line in read_data:
out_line = re.sub(r".*\[([^]]*)\].*", r"\1", line)
out_line = re.sub(r" ", r"", out_line)
out_line = re.sub(r"'", r"", out_line)
out_data.append(out_line)
# do whatever you want with out_data here
s=r"dasdad [some where, dsadasd '''' sadads] hoda"
re.sub(r'[\'\s]*', '', re.sub(r'.*\[([^]]*)\].*', r'\1', s))
输出:
somewhere,dsadasdsadads
对于喜欢这些东西的人来说,这是丑陋的单线:
>>> [f for f in open("foo.txt", 'r')]
["some string ['foo'] [b a r] [baz] [] extra stuff\n"]
>>> [re.sub("[ ']", "", s) for s in re.findall("\[(.*?)\]", f) for f in open("foo.txt")]
['foo', 'bar', 'baz', '']
解释,最好通过向后阅读代码来解释:
open()
默认为只读。re.findall("\[(.*?)\]", f)
提取 的内容[..]
。'
什么都没有(""
)。