问题描述
我正在使用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.
问题是我无法区分每个潜在的列,因为它们之间只有一个空格,并且在“具有相关信息的许可”中也有空格。
因此,我考虑过从Keywordcategory输入所有关键字,以便可以完成这一部分。但是我该如何处理“具有相关信息的同意”?
谢谢
解决方法
尝试这样的事情:
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()