如何在Python上从文本文件中提取总和数据

问题描述

我有一个包含6列的文本文件txt: 1.性别(男/女)2.年龄3.身高4.体重5 .- / + 6.邮政编码

我需要从此文本中找到多少个男性-符号。 (例如:从txt中,30 M(男性)为-)

所以我只需要最后一个数字。

从逻辑上讲,我需要使用Column1和column 5,但是我在尽力使最后只获得一个(和)数字。

这是文本的内容

M 87  66 133 - 33634
M 17  77 119 - 33625
M 63  57 230 - 33603
F 55  50 249 - 33646
M 45  51 204 - 33675
M 58  49 145 - 33629
F 84  70 215 - 33606
M 50  69 184 - 33647
M 83  60 178 - 33611
M 42  66 262 - 33682
M 33  75 176 + 33634
M 27  48 132 - 33607

我现在正在得到结果...,但是我希望M和正数都可以。如何将其添加到事件中?

f=open('corona.txt','r')
data=f.read()
occurrences=data.count('M')
print('Number of Males that have been tested positive:',occurrences)

解决方法

您可以这样分割行:

occurrences = 0
with open('corona.txt') as f:
    for line in f:
        cells = line.split()
        if cells[0] == "M" and cells[4] == "-":
            occurrences += 1
print("Occurrences of M-:",occurrences)

但是最好使用csv模块或pandas进行此类工作。

,

如果您要处理大量的文本和列数据,我建议您开始学习pandas

对于此任务,如果您的csv是每行一条记录,并且用空格分隔:

import pandas as pd
d = pd.read_csv('data.txt',names=['Sex','Age','Height','Weight','Sign','ZIP'],sep=' ',index_col=False)

d[(d.Sex=='M') & (d.Sign=='-')].shape[0] # or
len(d[(d.Sex=='M') & (d.Sign=='-')]) # same result,in this case = 9

Pandas是一个非常广泛的软件包。该代码的作用是从您的csv数据中构建一个DataFrame,为每列命名。然后从此每一行中选择两个条件Sex == 'M'Sign == '-'所在的行,并报告由此找到的记录数。

我建议开始here