簡體   English   中英

從python中的文本文件中讀取特定列

[英]Reading specific columns from a text file in python

我有一個文本文件,其中包含一個由數字組成的表格,例如:

5 10 6

6 20 1

7 30 4

8 40 3

9 23 1

4 13 6

例如,如果我想要只包含在第二列中的數字,我如何將該列提取到列表中?

f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

你可以使用列表理解來做同樣的事情

print([x.split(' ')[1] for x in open(file).readlines()])

關於split()文檔

string.split(s[, sep[, maxsplit]])

返回字符串s的單詞列表。 如果可選的第二個參數 sep 不存在或 None ,則單詞由任意的空白字符字符串(空格、制表符、換行符、返回、換頁符)分隔。 如果第二個參數 sep 存在而不是 None,則它指定一個字符串作為單詞分隔符。 返回的列表將比字符串中分隔符的非重疊出現次數多一項。

所以,你可以省略我使用的空間,只做x.split()但這也會刪除制表符和換行符,請注意這一點。

您有一個空格分隔文件,因此請使用專為讀取分隔值文件而設計的模塊csv

import csv

with open('path/to/file.txt') as inf:
    reader = csv.reader(inf, delimiter=" ")
    second_col = list(zip(*reader))[1]
    # In Python2, you can omit the `list(...)` cast

zip(*iterable)模式可用於將行轉換為列,反之亦然。 如果您正在逐行閱讀文件...

>>> testdata = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]

>>> for line in testdata:
...     print(line)

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

...但需要列,您可以將每一行傳遞給zip函數

>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])

>>> for line in testdata_columns:
...     print(line)

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

我知道這是一個老問題,但沒有人提到當你的數據看起來像一個數組時,numpy 的loadtxt會派上用場:

>>> import numpy as np
>>> np.loadtxt("myfile.txt")[:, 1]
array([10., 20., 30., 40., 23., 13.])

您可以使用帶有列表理解的zip函數:

with open('ex.txt') as f:
    print zip(*[line.split() for line in f])[1]

結果 :

('10', '20', '30', '40', '23', '13')

首先,我們打開文件並作為datafile然后我們應用.read()方法讀取文件內容,然后我們拆分數據,返回如下內容: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6']並且我們在這個列表上應用了列表切片,從索引位置 1 的元素開始並跳過接下來的 3 個元素,直到它到達循環的末尾。

with open("sample.txt", "r") as datafile:
    print datafile.read().split()[1::3]

輸出:

['10', '20', '30', '40', '23', '13']

它可能有幫助:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM