[英]How to read a text file and write it word by word into another file in python?
我有这样的文本文件:
this is a text file.
我想将它保存到另一个文件中,如下所示:
this
is
a
text
file
每个单词都进入了新的界限。 我也有这个非常简单的代码:
with open("test.txt", encoding = 'utf-8') as f:
for line in f:
for word in line.split():
print(word)
with open("test1.txt","a") as f1:
f1.write(word)
但是在打印之后,所有的单词都会写在一起。 你能帮我个忙吗? (只是一点暗示我应该怎么做)
当你这样做时:
for word in line.split():
实际上你正在遍历这个列表:
['this', 'is', 'a', 'text', 'file.']
因为你split
了空格。 然后当你把它写回"test1.txt","a"
,你正在编写那个列表中的所有内容而没有任何分隔符或空格,所以这是你的输出:
thisisatextfile.
现在,如果你想要每行上的每个单词,只需要写下与"\\n"
连接的每个单词,(新行字符)。
我对您的代码进行了一些更改,应该如下所示:
with open("test.txt", 'r') as f, open("test1.txt", 'w') as f1:
for line in f:
f1.write('\n'.join(line.split()))
f1.write('\n')
让我们仔细看看最重要的一行: f1.write('\\n'.join(line.split()))
。
str.split()
会将字符串拆分为空白字符列表。 (标签,空格,换行符)。 因此'word1 word2\\nword3\\tword4'.split()
将是['word1', 'word2', 'word3', 'word4']
。
str.join(<iterable>)
将迭代与给定的字符串连接在一起。 '\\n'.join(['word1', 'word2', 'word3', 'word4'])
是'word1\\nword2\\nword3\\nword4'
这个简单的脚本可以解决您的问题:
f=open("test.txt")
fw=open("test1.txt", 'w')
for line in f.readlines():
for word in line.split(" "):
print(word)
fw.write(word+"\n")
fw.close()
您应该只打开一次输出文件。
with open("test.txt", encoding = 'utf-8') as f:
with open("test1.txt","w") as f1:
for line in f:
for word in line.split():
print(word)
f1.write(word + '\n')
但如果您想坚持使用您的解决方案,只需在word
后添加+ '\\n'
。 这将在您添加到文件的单词后创建换行符。
write
不写任何你不写的东西,所以你必须告诉它明确地写一个新行"\\n"
。 或者,您可以使用自动放置新行的打印功能,以获得如下所需的结果:
print(word,file=f1)
在python 3中,在python 2中是
print >>f1, word
在你的情况下将是
with open("test.txt") as f, open("test1.txt","a") as f1:
for line in f:
temp="\n".join(line.split())
print(temp)
print(temp,file=f1)
那样你所看到的就是你得到的
我会选择以下内容,假设test.txt是输入,out.txt是输出:
with open('test.txt', 'r') as f:
o = f.read()
with open('out.txt', 'a') as f:
f.write('\n'.join(o.split()))
line = 'this is a text file'
line = line.replace(' ', '\n')
print(line)
输出:
this
is
a
text
file
使用上面的方法打开并写入您的文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.