我想在文件中的一个点之后创建换行符。
例如:
Instr()
输出:
If Range("A" & i) Like "*[*^]*[*^]*" Then
我试过这样,但不知何故它不起作用:
Hello. I am damn cool. Lol
你可以帮助我吗?
我不仅仅需要换行符,我想在单个文件中的每个点后面换行。它应遍历整个文件,并在每个点后创建换行符。
提前谢谢!
答案 0 :(得分:3)
这应该足以做到这一点:
with open('file.txt', 'r') as f:
contents = f.read()
with open('file.txt', 'w') as f:
f.write(contents.replace('. ', '.\n'))
答案 1 :(得分:2)
您可以split基于.
创建字符串并存储在列表中,然后打印出列表。
s = 'Hello. I am damn cool. Lol'
lines = s.split('.')
for line in lines:
print(line)
如果这样做,输出将为:
Hello
I am damn cool
Lol
要删除前导空格,您可以根据.
(带空格)进行拆分,或者在打印时使用lstrip()
。
所以,要为文件执行此操作:
# open file for reading
with open('file.txt') as fr:
# get the text in the file
text = fr.read()
# split up the file into lines based on '.'
lines = text.split('.')
# open the file for writing
with open('file.txt', 'w') as fw:
# loop over each line
for line in lines:
# remove leading whitespace, and write to the file with a newline
fw.write(line.lstrip() + '\n')