简体   繁体   English

Python:如何从 csv 中分离字符串和整数的混合?

[英]Python: How do I separate a mix of strings and integers from a csv?

import os
import csv
import pandas as pd
import itertools


data = r"C:\Users\chase\Documents\Exercise\MA Exercise_20190328-2"
for root, dirs, files in os.walk(data):
    for file in files:
        if file.endswith(".txt"):
            print(os.path.join(root, file))

    df = open("PikesPeak_Males.txt", "r")
    if df.mode == "r":
        contents = df.read()
        print(contents)

    with open("PikesPeak_Males.txt", "r") as in_file:
        stripped = (line.strip() for line in in_file)
        lines = (line.split(",") for line in stripped if line)
        with open("PikesPeak_Males.csv", "w") as out_file:
            writer = csv.writer(out_file)
            writer.writerow(("Place", "Div/Tot", "Number", "Name", "Age", "Hometown", "Gun Time", "Net Time", "Pace"))
            writer.writerows(lines)

So I have a dataset of running times for Racers.所以我有一个赛车手的运行时间数据集。 I converted the text file to a csv however, I want to split all the data into the following columns "Place", "Div/Tot", "Number", etc... But I am not sure how to do it as there isn't any commas or features to split the lines by.我将文本文件转换为csv但是,我想将所有数据拆分为以下列“Place”、“Div/Tot”、“Number”等......但我不知道该怎么做没有任何逗号或功能来分割行。 The main goal is to calculate the mean running time of the racers.主要目标是计算赛车手的平均跑步时间。 This is how it looks now:这是它现在的样子: 在此处输入图片说明

Example of how I want my csv to look:我希望我的 csv 看起来如何的示例:

在此处输入图片说明 PikesPeak_Male.txt PikesPeak_Male.txt

PikesPeakData派克峰数据

Check what are the separators in the .txt file.检查 .txt 文件中的分隔符是什么。 If they are tabs use tabs as separator when reading the csv:如果它们是制表符,则在读取 csv 时使用制表符作为分隔符:

pd.read_csv("filename.csv", header=None, delimiter=r"\t")

If separators are multiples of spaces first make one pass over the .txt file to convert multiples of spaces to single space or some other character ("\\t",",",...) and then use the chosen character as a separator.如果分隔符是空格的倍数,首先通过 .txt 文件将多个空格转换为单个空格或其他一些字符(“\\t”、“、”、...),然后使用所选字符作为分隔符.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM