[英]Read data seperated with tab from file in python
如果我有以下文件:
Pig
06-13-01 56.2
06-13-02 59.2
06-13-03 54.3
.
.
.
Cow
06-13-01 201.2
06-13-02 204.1
06-13-03 205.6
.
.
.
並希望創建一個 object 的實例,其中包含動物的數據以及相關的日期和重量(由制表符分隔的值)。 我如何在我的主程序中做到這一點?
我從這個開始:
with open(filnamn, encoding="utf-8") as file:
dateAndWeight = []
lines = fil.readlines()
lines = [line.rstrip() for line in lines]
stepsBetweenName = 68
numberOfAnimals = int(len(lines)/stepsBetweenName)`
但這僅僅是開始。 有人有建議嗎?
您的數據在動物名稱和制表符分隔的數據之間交替。 這非常適合itertools.groupby
根據列數等條件創建自己的迭代器。
在此示例中,只要行數在 1 和非 1 之間變化, groupby
就會開始新的子迭代。 當它為 1 時,你知道你有一個新動物。 非 1 時,您有數據行。 在這里,我剛剛建立了一個字典,將動物名稱映射到它的日期/重量信息。
import itertools
import io
import csv
# test file
file = io.StringIO("""Pig
06-13-01\t56.2
06-13-02\t59.2
06-13-03\t54.3
Cow
06-13-01\t201.2
06-13-02\t204.1
06-13-03\t205.6""")
# will hold `animal:[[date, weight], ...]` associations
animal_map = {}
# data is TSV file
reader = csv.reader(file, delimiter="\t")
# Group by rows of length 1 which start a new set of animal date, weight pairs
for new_animal, rows in itertools.groupby(reader, lambda row: len(row) == 1):
if new_animal:
# get animal from first row
animal = next(rows)[0]
else:
# add animal and data to map
animal_map[animal] = list(rows)
del animal
print(animal_map)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.