簡體   English   中英

將 csv 行中的文本文件列轉換為 python?

[英]convert text file column in csv row in python?

我有 data.txt 看起來像這樣:

 Ball stump inner shocks bat mask gloves helmet grip pad jersey shoe cap 1 5 9 13 2 14 3 7 11 4 8 12 16

 from itertools import groupby, chain with open("file.txt", "r") as fin,\ open("file.csv", "w") as fout: for key, group in groupby(fin, key=lambda line: bool(line.strip())): if key: zipped = zip(*(line.rstrip().split() for line in group)) fout.write(",".join(chain(*zipped)) + "\n")

我想將此 txt 文件轉換為 csv output 我希望看到: output

下面是如何通過解釋實現這一點的代碼

# 1. importing the required packages
import re
import pandas as pd

# 2. Reading your file
with open('data.txt') as f:
    filedata = f.read()

# 3. converting all the multiple spaces to single space
filedata = re.sub(r"\s+", " ", filedata).split(' ')

# 4. Extracting the mid length to get the headers and data to convert into csv structure
mid_len = int(len(filedata)/2)
header, data = [x for x in filedata[:mid_len]], [x for x in filedata[mid_len:]]

# 5. Converting the data into dataframe and from there the dataframe object can be used to save this data into csv, excel or different other formats.
df = pd.DataFrame(data).T
df.rename(columns=dict(zip(df.columns,header)))

# 6. Output
    Ball    stump   inner   shocks  bat mask    gloves  helmet  grip    pad jersey  shoe    cap
0   1   5   9   13  2   14  3   7   11  4   8   12  16

這是一個沒有外部庫的版本:

import re

with open('file.txt', 'r') as input_stream, \
            open('file.csv', 'w+') as output_stream:
    
        content = ''.join(input_stream.readlines())  # Load all the input file in one place
        data = sorted(
            zip(
                re.findall(r'[a-zA-Z]+', content),   # Get the header
                re.findall(r'[0-9]+', content)       # Get the values
            ), key=lambda x: int(x[1])               # Order by value
        )
    
        output_stream.write(f"{','.join([f'{k}' for (k, _) in data])}\n")  # Write CSV header
        output_stream.write(f"{','.join([f'{v}' for (_, v) in data])}\n")  # Write CSV values

Output

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM