python读取用空格分隔的文字_Python:从类似readlin的文件中读取空格分隔的字符串...
您需要創建一個包裝函數;這非常簡單:def read_by_tokens(fileobj):
for line in fileobj:
for token in line.split():
yield token
注意.readline()在遇到換行符之前,不只是逐字讀取文件;文件是在塊(緩沖區)中讀取的,以提高性能。
上面的方法按行讀取文件,但會產生對空白的拆分結果。像這樣使用:with open('somefilename') as f:
for token in read_by_tokens(f):
print(token)
因為read_by_tokens()是一個生成器,您需要直接在函數結果上循環,或者使用^{} function逐個獲取標記:with open('somefilename') as f:
tokenized = read_by_tokens(f)
# read first two tokens separately
first_token = next(tokenized)
second_token = next(tokenized)
for token in tokenized:
# loops over all tokens *except the first two*
print(token)
總結
以上是生活随笔為你收集整理的python读取用空格分隔的文字_Python:从类似readlin的文件中读取空格分隔的字符串...的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: python 底层原理_Python字典
- 下一篇: python入门之函数调用educode
