重新发布它,因为它被错误地标记为重复。这篇文章是linked但没有回答我的问题
我是 Python 新手,我有一个如下所示的文本字符串。我需要帮助将其转换为表格。我尝试通过创建字典来做到这一点,但是,每行中的列数并不总是相同,这会产生一个问题。另外,文本中还有像“stock”这样的列,我在最终输出中不需要这些列
删除空行和其他信息后。文本文件如下所示。
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
stock
10
Number
20
Fruit
grape
price
12
这是我想要的表格格式输出,第二行的价格应为空值,第三行的数字应为空值。
Fruit price Number
Apple 30 10
kiwi 20
grape 12
最佳答案
您可以使用pandas
来创建这样的表:
import pandas as pd
text = '''XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
Number
20
Fruit
grape
price
12'''
data = {'Fruit': [], 'price': [], 'Number': []}
lines = text.split()
for i in range(len(lines)):
if i+5 < len(lines) and lines[i] == 'Fruit' and lines[i+2] == 'price' and lines[i+4] == 'Number':
data['Fruit'].append(lines[i+1])
data['price'].append(lines[i+3])
data['Number'].append(lines[i+5])
elif i+3 < len(lines) and lines[i] == 'Fruit' and lines[i+2] == 'Number':
data['Fruit'].append(lines[i+1])
data['price'].append('')
data['Number'].append(lines[i+3])
elif i+3 < len(lines) and lines[i] == 'Fruit' and lines[i+2] == 'price':
data['Fruit'].append(lines[i+1])
data['price'].append(lines[i+3])
data['Number'].append('')
df = pd.DataFrame(data)
print(df)
结果:
Fruit price Number
0 Apple 30 10
1 kiwi 20
2 grape 12
您还可以将结果保存到 CSV:
df.to_csv('result.csv')
关于python - 从文本字符串创建表/csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54649839/