从 table 中提取数据,在 Python 中使用不同数量的空格
Extract data from table with different amount of spaces in between in Python
我想从 Python 中的 .txt 文件中提取数据:
Pennsylvania (105161,985645) 189562.58 0
California (586253,566851) 556064.21 0
Kentucky (875956,213560) 985022.85 1
Oklahoma (485010,506222) 521446.15 0
两个特定列之间的空格数始终相同,但有时会有所不同。列条目本身没有空格。
我想将一行的所有条目汇集到一个元组中,并且我想将所有元组放入一个列表中。如何从文件中提取条目?
我尝试使用 line.split,但我不确定如何使用它,因为列之间的空格数不同。
如有任何帮助,我们将不胜感激
使用pandas:
df = pd.read_csv('myfile.txt', header=None, sep="\s+")
输出:
0 1 2 3
0 Pennsylvania (105161,985645) 189562.58 0
1 California (586253,566851) 556064.21 0
2 Kentucky (875956,213560) 985022.85 1
3 Oklahoma (485010,506222) 521446.15 0
line.split() 即使您改变空格数也会起作用。
with open("a.txt", "r") as fd:
myList = []
for i in fd.readlines(): # iterate over each line
mytuple = tuple(m for m in i.split()) # generate tuples
myList.append(mytuple) # append tuples to list
print(myList)
输出:
[('Pennsylvania', '(105161,985645)', '189562.58', '0'), ('California', '(586253,566851)', '556064.21', '0'), ('Kentucky', '(875956,213560)', '985022.85', '1'), ('Oklahoma', '(485010,506222)', '521446.15', '0')]
我想从 Python 中的 .txt 文件中提取数据:
Pennsylvania (105161,985645) 189562.58 0
California (586253,566851) 556064.21 0
Kentucky (875956,213560) 985022.85 1
Oklahoma (485010,506222) 521446.15 0
两个特定列之间的空格数始终相同,但有时会有所不同。列条目本身没有空格。
我想将一行的所有条目汇集到一个元组中,并且我想将所有元组放入一个列表中。如何从文件中提取条目?
我尝试使用 line.split,但我不确定如何使用它,因为列之间的空格数不同。
如有任何帮助,我们将不胜感激
使用pandas:
df = pd.read_csv('myfile.txt', header=None, sep="\s+")
输出:
0 1 2 3
0 Pennsylvania (105161,985645) 189562.58 0
1 California (586253,566851) 556064.21 0
2 Kentucky (875956,213560) 985022.85 1
3 Oklahoma (485010,506222) 521446.15 0
line.split() 即使您改变空格数也会起作用。
with open("a.txt", "r") as fd:
myList = []
for i in fd.readlines(): # iterate over each line
mytuple = tuple(m for m in i.split()) # generate tuples
myList.append(mytuple) # append tuples to list
print(myList)
输出:
[('Pennsylvania', '(105161,985645)', '189562.58', '0'), ('California', '(586253,566851)', '556064.21', '0'), ('Kentucky', '(875956,213560)', '985022.85', '1'), ('Oklahoma', '(485010,506222)', '521446.15', '0')]