我有一个看起来像这样的文件:
TOTO TATA
TUTU TITI PAPA
AAA BBB CCCC
我希望能够用其他东西替换开头的空格。
例如:
eeeTOTO TATA
TUTU TITI PAPA
eeeeeeeeeAAA BBB CCCC
看起来很简单,但它对我不起作用。
这是我错误地尝试的:
#!/usr/bin/python
#open the file
fs = open("./Tst.tst", 'r')
fd = open("./Out.tst", 'w')
print fs.read()
print fd.read()
for line in fs:
fd.write(line)
for char in line:
if (" ") in char:
char = char.replace(" ", "e" )
fd.write(char)
else:
print char
fd.close()
fs.close()
答案 0 :(得分:2)
您可以将re.sub
与回调一起使用:
In [979]: import re
In [980]: for x in lines.splitlines():
...: print(re.sub('^ +', lambda k: 'e' * len(k.group(0)), x))
...:
eeeTOTO TATA
TUTU TITI PAPA
eeeeeeeeeAAA BBB CCCC
作为一个完整的例子,请考虑:
def foo(k):
'e' * len(k.group(0))
with open("./In.txt", 'r') as fs, open("./Out.txt", 'w') as fd:
lines = fs.read()
for x in lines.splitlines():
print(re.sub('^ +', foo, file=fd)
当遇到匹配时,匹配对象被传递给回调,回调返回另一个字符串作为替换。
答案 1 :(得分:0)
对于非正则表达式解决方案,我可以提出这个问题。
<强>声明强>
它适用于示例输入,但您必须对其进行更多测试才能清除错误;如果有的话。
# text = ' TOTO TATA '
# text = 'TUTU TITI PAPA'
text = ' AAA BBB CCCC'
character_spot = False
num_empty_spots = 0
unwanted_text = ' '
replacement_text = 'e'
# this loop counts the number of empty spots in your string
for char in text:
if char != unwanted_text and not character_spot:
character_spot = True
print 'Character exists'
else:
if not character_spot:
num_empty_spots += 1
print 'Empty spot'
# this replaces the first 'num_empty_spots' occurences of the unwanted_text
text = text.replace(unwanted_text, replacement_text, num_empty_spots)
print text