如何在python中的文本文件中获取统计信息

时间:2018-10-29 10:03:26

标签: python

我有一个大文本文件,例如小例子:

小例子:

chr1    10385347    10385379    11  chr1    10000000    11000000
chr1    10385348    10385379    40  chr1    10000000    11000000
chr1    10385348    10385379    40  chr1    10000000    11000000
chr1    10385348    10385379    381 chr1    10000000    11000000
chr1    10561009    10561040    12  chr1    10000000    11000000
chr1    10561009    10561040    24  chr1    10000000    11000000
chr1    10647768    10647799    68  chr1    10000000    11000000
chr1    10958095    10958126    17  chr1    10000000    11000000
chr1    11196862    11196893    39  chr1    11000000    12000000
chr1    11921548    11921579    56  chr1    11000000    12000000
chr1    13967589    13967620    111 chr1    13000000    14000000
chr1    15290638    15290669    11  chr1    15000000    16000000
chr1    15587268    15587299    32  chr1    15000000    16000000
chr1    15587268    15587299    13  chr1    15000000    16000000

我想计算第6列和第7列相同的行数。然后创建一个新文件,其中包含4 columns,“ column5”,“ column6”,“ column7”在内的count。 这个小例子的输出看起来像这样:

预期输出:

chr1    10000000    11000000    8
chr1    11000000    12000000    2
chr1    13000000    14000000    1
chr1    15000000    16000000    3

我正在尝试在python中这样做,并编写了以下代码:

file = open('infile.txt', 'rb')
line = []
for i in file:
    line.append(i.split())
    count = 0
    new_list = []
    for j in range(len(line)):
        if line[j] == line[j-i]:
            count+=1
            new_list.append(count)

with open(outfile, "w") as f:
    for item in new_list:
        f.write("%s\n" % item)

,但不会返回我期望的输出。你知道如何解决吗?

5 个答案:

答案 0 :(得分:2)

Python之所以出名是因为不必编写这样的整体代码。也许,如果将其拆分为多个函数调用,将更易于阅读和调试。

只是没有代码的提示:

  1. 从文件中读取行。
  2. 用一个空格替换所有空格(为此使用正则表达式)
  3. 根据您的条件过滤所有行(匹配第6列和第7列)
  4. 将过滤后的行写到文件中。

答案 1 :(得分:1)

不是答案,但是它将帮助您顺利通过。用分隔符读取文件中的每一行,在您的情况下为2个空格。拆分每一行,并分别获取第5、6部分,并将它们组合起来,使其成为字典和值的键,并将其设为1。对文件中的每一行进行迭代,生成键,每次找到键时将其递增1。我假设col-1对于所有行都是相同的。否则,还请在密钥中包含col-1。

您可以对文件中的每一行执行以下操作,并在读取所有行的末尾获得统计信息。

import re
s="chr1    10385347    10385379    11  chr1    10000000    11000000"
re.sub(' +',' ',s)
res={}
s=re.sub(' +',' ',s)
res[s.split(" ")[5]+"-"+s.split(" ")[6]]=1

答案 2 :(得分:0)

这是我为您解决问题的解决方案。其他人可以发表评论,看看有没有更有效的方法。

result = []

with open('infile.txt', 'rb') as infile:
    text = infile.read()
    for line in text.splitlines():
        fields = line.split()

        if any(x['6th'] == fields[5] and x['7th'] == fields[6] for x in result):
            for x in result:
                if x['6th'] == fields[5] and x['7th'] == fields[6]:
                    x['counter'] += 1
                    break
        else:
            result.append({
                '5th': fields[4],
                '6th': fields[5],
                '7th': fields[6],
                'counter': 1
            })

with open('outfile.txt', 'w') as outfile:
    for x in result:
        outfile.write('{} {} {} {}\n'.format(
            x['5th'],
            x['6th'],
            x['7th'],
            x['counter']
        ))

由于我不知道您项目的上下文和值的含义,因此我只放置了5th6th7th之类的虚拟名称。

答案 3 :(得分:-1)

您可能要考虑的一种方法是将文本文件加载为Pandas数据框,然后使用库函数从那里开始工作。需要注意的是,这种方法在处理非常大的数据集时会很慢。

您将需要导入的Pandas和Numpy库

using UnityEngine;

using UnityEngine.Networking;

public class EnemySpawner : NetworkBehaviour
{

public GameObject enemyPrefab;
public int numberOfEnemies;

public override void OnStartServer()
{
    for (int i = 0; i < numberOfEnemies; i++)
    {
        var spawnPosition = new Vector3(
            Random.Range(-5.0f, 5.0f),
            0.0f,
            Random.Range(-5.0f, 5.0f));

        var spawnRotation = Quaternion.Euler(
            0.0f,
            Random.Range(0, 180),
            0.0f);

        var enemy = (GameObject)Instantiate(enemyPrefab, spawnPosition, spawnRotation);
        NetworkServer.Spawn(enemy);
    }
}
}

接下来,您可以将数据作为数据框导入。

import numpy as np
import pandas as pd

哪个生成以下数据帧:

#Passing `names = ['column1','etc']` as an argument lets us define the headers to be used for each column
#As the name suggests, `delim_whitespace=True` makes whitespace the delimiter.
df = pd.read_csv('filename.txt',names=['column1','column2','column3','column4','column5','column6','column7'], delim_whitespace=True)

设置数据框后,我们现在可以使用Pandas函数来帮助操纵数据框。

要创建一个新的数据帧,其中包含重复的第5,6和7行的计数,您可以使用以下内容(我假设您在第5行中除了'chr1'以外还有其他值,所以也许我们想在计算重复项时包括该行吗?):

   column1   column2   column3  column4 column5   column6   column7
0     chr1  10385347  10385379       11    chr1  10000000  11000000
1     chr1  10385348  10385379       40    chr1  10000000  11000000
2     chr1  10385348  10385379       40    chr1  10000000  11000000
3     chr1  10385348  10385379      381    chr1  10000000  11000000
4     chr1  10561009  10561040       12    chr1  10000000  11000000
5     chr1  10561009  10561040       24    chr1  10000000  11000000
6     chr1  10647768  10647799       68    chr1  10000000  11000000
7     chr1  10958095  10958126       17    chr1  10000000  11000000
8     chr1  11196862  11196893       39    chr1  11000000  12000000
9     chr1  11921548  11921579       56    chr1  11000000  12000000
10    chr1  13967589  13967620      111    chr1  13000000  14000000
11    chr1  15290638  15290669       11    chr1  15000000  16000000
12    chr1  15587268  15587299       32    chr1  15000000  16000000
13    chr1  15587268  15587299       13    chr1  15000000  16000000

这给了我 dfnew

#groupby(['column5','column6','column7']) means that we're looking for duplicates across columns 5,6,7 and grouping them together
#.size() returns the number of duplicates aka the size of each group
#.reset_index().rename(columns={0:'count'}) is just giving the new column of duplicate numbers a header 'count'
dfnew = df.groupby(['column5','column6','column7']).size().reset_index().rename(columns={0:'count'})

有了这个新的数据框,用数据生成文件很简单。

  column5   column6   column7  count
0    chr1  10000000  11000000      8
1    chr1  11000000  12000000      2
2    chr1  13000000  14000000      1
3    chr1  15000000  16000000      3

最终文件如下:

#The argument sep=' ' indicates that one space is used as a delimiter for the file
#The argument index=False omits the row indexes when writing to the file
df3.to_csv('newfile.txt',sep=' ',index=False)

我希望这会有所帮助!

使用的参考文献:

Pandas Docs

How to count duplicate rows in pandas dataframe?

答案 4 :(得分:-1)

统计摘要

进口大熊猫

url =“将csv文件放在此处”

在此处输入任何csv文件url或在此处加载csv

names = ['preg','plas','pres','skin','test','mass','pedi','age','class']

数据= pandas.read_csv(URL,名称=名称)

描述= data.describe()

打印(说明)