繁体   English   中英

使用python将txt文件中的数据排序到列中

[英]Sort data from txt file into columns using python

我正在使用 Python 我有一个 txt 文件,其中包含这样组织的数据:

acertainfilepathendingwith.txt T+anumber Keywordcategory notimportantnumber anothernotimportantnumber asentencewithrelevantinformation

例子:

C:\Test.txt T5 Plane 2848 3102 An apple a day keeps the doctor away.

我想创建一个如下所示的数据框:

acertainfilepathendingwith.txt|Keywordcategory|asentencewithrelevantinformation

所以对于我的例子:

C:\Test.txt|Plane|An apple a day keeps the doctor away.

问题是我无法区分每个潜在的列,因为它们之间只有一个空格,并且在“asentencewithrelevantinformation”中也有空格。

所以我想从 Keywordcategory 中输入所有关键字,所以这部分是可行的。 但是我该如何处理“asentencewithrelevantinformation”呢?

谢谢

尝试这样的事情:

with open("test.txt", "r") as f:
    for line in f:
        a = line.split()      
        out = a[0]+'|'+a[2]+'|'                
        for x in a:
            if a.index(x) > 4:
                out += x+' '
        print(out)
        a.clear()

编辑:

with open("test.txt", "r") as f:
    for line in f:
        if line == '\n':
            pass
        else:
            a = line.split()      
            out = a[0]+'|'+a[2]+'|'                
            for x in a:
                if a.index(x) > 4:
                    out += x+' '
            print(out)
            a.clear()

暂无
暂无

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

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