2017-07-08 72 views
1

一個獨立的行我有一條線在我的文本文件類似下面的一行:單獨字符串的話在Python

hi everyone this is good 
the weather is good  yes 

我想寫這樣一個行中的每個字符串:

hi 
    everyone 
    this 

我該怎麼辦?我不知道每個字符串之間的空格數量。

謝謝

我用這個方法,但它didn't工作

text_file = open("1.txt","r") 
for line in text_file : 
    lline = list(line) 
    lline.replace(" ", "") 
    line1 = lline.join() 
    file.write(line1) 

回答

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()

+0

爲什麼不在字符串類本身中使用split?沒有理由說'split'會做我想做的工作。 – officialaimm

+1

@officialaimm,你是對的,那會更好:) – Elisha

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 
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 

它會打印出結果。

+0

它的工作,但如果我的字符串是其他語言我應該怎麼做 – alish

+1

你是什麼意思其他語言? – Park

1

試試這個,只要確保文件是打開的文件連接寫入。

text_file = open("1.txt","r") 
for line in text_file : 
    lline = line.split() 
    line1 = '\n'.join(lline) 
    file.write(line1)