我的文本文件中有一行,如下面一行:
hi everyone this is good
the weather is good yes
我想将每个字符串写成一行,如下所示:
hi
everyone
this
我该怎么办?我不知道每个字符串之间的空格数。
谢谢
我使用了这种方法,但它不起作用
text_file = open("1.txt","r")
for line in text_file :
lline = list(line)
lline.replace(" ", "")
line1 = lline.join()
file.write(line1)
答案 0 :(得分:4)
您可以按空格分割线条并展平列表:
lines = ['hi there', 'how are you today']
tokens = [token for line in lines for token in line.split()]
# tokens: ['hi', 'there', 'how', 'are', 'you', 'today']
从文件中读取时,代码应为:
with open('1.txt', 'rt') as text_file:
tokens = [token for line in text_file for token in line.split()]
target_file.write('\n'.join(tokens))
修改,感谢officialaimm的评论,示例已从re.split(r'\s+', line)
简化为line.split()
。
答案 1 :(得分:2)
您可以使用拆分功能。
像:
text_file = open("1.txt","r").read()
for i in text_file.strip().split('\n'):
[print(j) for j in i.split()]
----
hi
everyone
this
is
good
the
weather
is
good
yes
它会打印结果。
答案 2 :(得分:1)
使用re.sub
:
In [227]: import re
In [228]: line = '''hi everyone this is good
...: the weather is good yes'''
In [233]: print(re.sub('\s+', '\n', line, re.M | re.DOTALL))
hi
everyone
this
is
good
the
weather
is
good
yes
答案 3 :(得分:1)
试试这个,只需确保文件是打开的文件连接即可。
text_file = open("1.txt","r")
for line in text_file :
lline = line.split()
line1 = '\n'.join(lline)
file.write(line1)