我正在讀取製表符分隔的文本文件,其中每行以新行結尾。我在引用段中存在換行符的問題(該文本是由人類插入的,並且可能在一行中包含新行)。當文本可能包含'^ 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
。
請發佈一個鏈接到生成此輸出的實際輸入文件。如果這個行像這樣用tab作爲分隔符分隔,那麼必須有某個標籤。這將有助於重現您的行爲。 –
[輸入文件](https://docs.google.com/a/yotpo.com/document/d/1owDzmvfRR-wQ9dr3EoOa8a10tVypjfQ6AeqmnRXCg8I/pub) – Serendipity