Python将文件中空格变成换行的方法如何做,python换行,比如文件中有这样的字符串


比如文件中有这样的字符串:

a.txt

Rei9aiwe bohth4Zu Go3eimum iChieSh5iveeSh2J eiziV0bo lu2Efooz feey5Ohr

要转换成下面的形势:

b.txt

Rei9aiwebohth4ZuGo3eimumiChieSh5iveeSh2JeiziV0bolu2Efoozfeey5Ohr

如何做?

语言不限,PHP/Ruby/Python都可以。

既然语言不限,来一个另类的,目测没几个知道是什么语言

Import["a.txt"]~StringReplace~(" " -> "\n") // Export["b.txt", #] &

补充个ruby 版

open("b.txt", "w").puts open('a.txt').read.gsub " ", "\n"

python

myfile = open("a.txt")temp = ""for line in myfile.readlines():    for a in line.split():         temp +=  a + '\n'myfile.close()file_object = open('b.txt', 'w')file_object.writelines(temp)file_object.close()
sed 's/\s\+/\n/g' a.txt > b.txt

或者

tr ' ' '\n' < a.txt > b.txt

或者用 Python:

python -c 'open("b.txt", "w").write(open("a.txt").read().replace(" ", "\n"))'

这样的任务,超过一行的代码就实在是太浪费啦。

编橙之家文章,

评论关闭