假设我有一个文本文件(test.txt):
This is a
test
我的python代码:
f = open("test.txt")
x = f.readlines()
s = []
for i in x:
k = i.replace("a","not a")
s.append(k)
with open('output.txt', 'w') as a:
a.write(" ".join(s))
给出如下(output.txt):
This is not a
test
,但我不想要中间的空格。我想要这样写:
This is not a test
如何删除换行符?
立即连接每一行,然后用空白分隔整个字符串。然后你应该有可以循环和替换的单词,然后再连接在一起
replacements = {"a" : "not a"}
def replace(s):
if s in replacements:
return replacements[s]
return s
with open("test.txt") as f:
x = " ".join(l.strip() for l in f)
x = x.split()
print(" ".join(replace(s) for s in x))