2016-04-27 23 views
1

我正在讀取製表符分隔的文本文件,其中每行以新行結尾。我在引用段中存在換行符的問題(該文本是由人類插入的,並且可能在一行中包含新行)。當文本可能包含'^ M'和Python時,從文件中逐行讀取文本的最佳方法

例如:

「!偉大的感覺完全推薦它

超級舒適且持續時間!」

這基本上是以下文字:

Great feeling! Totally recommend it!^M\nSuper comfort and it lasts! 

我想讀這整個句子作爲一個對象,但仍可以通過換行分割文本文件中的行。

當我使用標準閱讀功能for line in file_object打破了「很棒的感覺!完全推薦它!」到一個對象和「超級舒適,它會持續!」當他們屬於同一個句子時不同的一個。

def readFromFile(self, filepath, delim = '\t'): 
     with open(filepath, 'r') as file_object: 
      for line in file_object: 
       yield line.strip().rstrip(os.linesep).split(delim) 

我期望的結果是「很棒的感覺!完全推薦!超級舒適,它持續!」

已更新: 這是我使用CSV閱讀器的功能,建議如下。

def readFromFile(self, filepath, delim = '\t'): 
    with open(filepath, 'r', newline='', encoding='utf-8') as file_object: 
     # Use the csv reader to split by delimiter and remove EOF. 
     # will handle newlines inside quoted sections of TSV files 
     reader = csv.reader(file_object, delimiter=delim) 
     # skip the headers 
     next(reader, None) 

     for line in reader: 
      # Each row read from the csv file is returned as a list of strings. 
      print(ascii(line)) 
      #yield line 
    return 

結果是:

[ '4', 'BNeU2UqihIwhRq9G3APK7b6ht2IZoJ21YUt4PlET',「超級舒服! ','真正推薦給那些尋求舒適和質量的人! ']

[' 5' , 'BNeU2UqihIwhRq9G3APK7b6ht2IZoJ21YUt4PlET', '偉大的感覺!', '完全推薦它!']

['\ nSuper舒適且持續時間! 「]

[」 5' ,‘B02uug6tF2uEA0Denhj0c9PV73y5PEOuKFmTCGb1’,‘這是一個巨大的按鈕’,「唧唧歪歪」]

這是很容易看到,for line in reader仍然打破了句與^M

+0

請發佈一個鏈接到生成此輸出的實際輸入文件。如果這個行像這樣用tab作爲分隔符分隔,那麼必須有某個標籤。這將有助於重現您的行爲。 –

+0

[輸入文件](https://docs.google.com/a/yotpo.com/document/d/1owDzmvfRR-wQ9dr3EoOa8a10tVypjfQ6AeqmnRXCg8I/pub) – Serendipity

回答

1

Python的內置csv.reader將處理的CSV/TSV文件引述部分內換行:https://docs.python.org/2/library/csv.html#csv.reader

在你的情況下,代碼可能是這個樣子:

import csv 

def readFromFile(filepath, delim = '\t'): 
    with open(filepath) as file_object: 
     for line in csv.reader(file_object, delimiter=delim): 
      print('here I am:', line) 

readFromFile('myfile.txt') 

它打印:

here I am: ['Great feeling! Totally recommend it!\nSuper comfort and it lasts!'] 
+0

csv.reader()中的'for line'仍然會打斷這個句子。如果我打印行,我會得到「很棒的感覺!完全推薦它!」和「\\ n超舒適,它持續!」在一個不同的對象。 – Serendipity

+0

@Sendndipity:不在我的系統上!我已經更新了我的答案,以包含您的示例輸入的完整工作代碼(包含兩行的文本文件,在文件的開頭和結尾處帶有雙引號)。我還在Python 2.7中爲該示例輸入包含了實際代碼的輸出。看看它是否與我提供的確切代碼在系統上不一樣。 –

+0

我正在使用Python3.5。此外,請注意,我有^ M linebreak,而不僅僅是'正常'linebreak – Serendipity

1

csv.reader是答案,但要正確使用它與Python 3,該文件應打開與newline='' as documented。特別要注意在鏈接的註腳:

如果沒有指定新行=「」時,嵌入引號字段內換行不會被正確解釋,並在使用平臺\ r \ n寫上一個額外的\ r linendings將被添加。指定newline =''應該始終安全,因爲csv模塊執行自己的(通用)換行處理。

import csv 
with open('test.txt','r',newline='') as f: 
    r = csv.reader(f,delimiter='\t') 
    for line in r: 
     print(ascii(line)) 

輸出(注意^M(CTRL-M)相當於\r轉義碼):

['Great feeling! Totally recommend it!\r\nSuper comfort and it lasts!'] 

要分割線:

print(line[0].split('\r\n')) # if \r\n is consistent. 

或者:

import re 
print(re.split(r'\r?\n',line[0])) # if \n or \r\n is possible. 
+0

我已經更新了我正在使用的代碼以及本示例不需要的輸出的問題。 – Serendipity

相關問題