从文本字符串创建 table/csv
Create a table/csv from text string
重新post编辑它,因为它被错误地标记为重复。这个 post 是 linked 但没有回答我的问题
我是 Python 的新手,我有一个看起来像这样的文本字符串。我需要帮助将其转换为 table。我尝试通过创建字典来做到这一点,但是,每行中的列数并不总是相同,这会产生一个问题。另外,文本中有像 "stock" 这样的列,我在最终输出中不需要这些
删除空行和其他信息后。文本文件如下所示。
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
stock
10
Number
20
Fruit
grape
price
12
这是我想要的 table 格式的输出,第二行的价格应为空值,第三行的数字应为空值。
Fruit price Number
Apple 30 10
kiwi 20
grape 12
您可以使用 pandas
创建这样的 table:
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')
如果你不想使用 Pandas:
,这是我想放在这个问题的第一个版本上的解决方案
#!/usr/bin/env python
import re
data = """
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
Number
20
Fruit
grape
price
12"""
def doit(data):
table = []
data = re.split(r'\s+', data)
currentFruit = None
while len(data):
line = data.pop(0)
if line == "Fruit":
if currentFruit:
table.append(currentFruit)
currentFruit = { 'name': data.pop(0) }
elif currentFruit:
currentFruit[line] = data.pop(0)
table.append(currentFruit)
print "%-9s%-9s%-9s" % ("Fruit", "price", "Number")
for fruit in table:
print "%-9s%-9s%-9s" % (fruit['name'],
fruit['price'] if 'price' in fruit else '',
fruit['Number'] if 'Number' in fruit else '')
doit(data)
重新post编辑它,因为它被错误地标记为重复。这个 post 是 linked 但没有回答我的问题
我是 Python 的新手,我有一个看起来像这样的文本字符串。我需要帮助将其转换为 table。我尝试通过创建字典来做到这一点,但是,每行中的列数并不总是相同,这会产生一个问题。另外,文本中有像 "stock" 这样的列,我在最终输出中不需要这些
删除空行和其他信息后。文本文件如下所示。
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
stock
10
Number
20
Fruit
grape
price
12
这是我想要的 table 格式的输出,第二行的价格应为空值,第三行的数字应为空值。
Fruit price Number
Apple 30 10
kiwi 20
grape 12
您可以使用 pandas
创建这样的 table:
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')
如果你不想使用 Pandas:
,这是我想放在这个问题的第一个版本上的解决方案#!/usr/bin/env python
import re
data = """
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
Number
20
Fruit
grape
price
12"""
def doit(data):
table = []
data = re.split(r'\s+', data)
currentFruit = None
while len(data):
line = data.pop(0)
if line == "Fruit":
if currentFruit:
table.append(currentFruit)
currentFruit = { 'name': data.pop(0) }
elif currentFruit:
currentFruit[line] = data.pop(0)
table.append(currentFruit)
print "%-9s%-9s%-9s" % ("Fruit", "price", "Number")
for fruit in table:
print "%-9s%-9s%-9s" % (fruit['name'],
fruit['price'] if 'price' in fruit else '',
fruit['Number'] if 'Number' in fruit else '')
doit(data)