【问题标题】:Convert Semicolon Separated Strings Text File to Columns and perform sorting in Python?将分号分隔的字符串文本文件转换为列并在 Python 中执行排序?
【发布时间】:2021-09-24 08:46:47
【问题描述】:

我有分号分隔的文本文件包含以下数据:

QWxxx1;Jan;2021;Rate;Customer;Operator;Online;100
QWxxx2;Jan;2021;Rate;Customer;Operator;Online;980
QWxxx4;Jan;2021;Rate;Customer;Operator;Offline;200
QWxxx5;Jan;2021;Rate;Customer;Operator;Online;1000
QWxxx6;Jan;2021;Rate;Customer;Operator;Offline;500

现在想将此数据转换为新文本文件(“.txt”)中的八列:

0         1      2       3          4    5         6      7
QWxxx1    Jan    2021    Customer        Online    100
QWxxx2    Jan    2021    Customer        Online    980
QWxxx4    Jan    2021    Customer        Offline          200  
QWxxx5    Jan    2021    Customer        Online    1000
QWxxx6    Jan    2021    Customer        Offline          500

->想要删除速率和运算符列。

->希望将第 4 列留空。

->如果我的第 5 列值为“离线”,则希望将数字移到下一列。

Python 代码:

    import pandas
    datafile = "path\.txt"
    newfile = "New_"+datafile
    f = open(newfile,"w")
    for str in open(datafile,"r"):
        str = str.split(';')
        df = pandas.DataFrame([str], columns =[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']) 
        f.write(str)
    f.close()

【问题讨论】:

  • 您的输出文本文件将不能用作分栏数据,因为“column” 4 不明确。这只有在列是固定宽度时才有效
  • @DarkKnight,发布后我将编辑该列,但首先我需要在给定列中对其进行排序

标签: python python-3.x python-requests


【解决方案1】:

您可以使用pandas.read_csv 读取您的文件,然后逐一应用您的转换,并使用pandas.to_csv 保存:

import pandas as pd

df = pd.read_csv('filename.csv', delimiter=';', header=None)  # read input
del df[3]                                     # remove column
df[5] = ''                                    # empty column
df.columns = range(df.shape[1])               # rename columns
df[7] = df[6].where(df[5].eq('Offline'), '')  # create new column with subset
df[6] = df[6].where(df[5].eq('Online'), '')   # replace existing column with subset
df.to_csv('newfile.csv', sep='\t', index=False)               # save to file

【讨论】:

  • 如果 OP 真的想要一个固定宽度的文件,将df.to_string() 写入结果文件可能更合适。
  • @SergeBallesta 是的,这是可能的,虽然目前模棱两可,但如果需要,我会更新(或者如果你愿意,可以随时更新)
  • @mozway,非常感谢它的工作! (Y)
【解决方案2】:

没有熊猫的帮助:-

with open('f.txt') as txtin:
    with open('f1.txt', 'w') as txtout:
        print('0       1    2     3        4    5        6     7     ', file=txtout)
        for line in [l.strip() for l in txtin.readlines()]:
            t = line.split(';')
            if t[6] == 'Online':
                c6 = t[7]
                c7 = ''
            else:
                c6 = ''
                c7 = t[7]
            txtout.write(f'{t[0]: <7} {t[1]: <4} {t[2]: <5} {t[4]: <9}     {t[6]: <8} {c6: <5} {c7: <5}\n')

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2021-01-23
    • 2018-02-22
    相关资源
    最近更新 更多