3 回答

TA貢獻1829條經驗 獲得超7個贊
不要重新發明輪子。使用csv模塊,例如DictReader:
import csv
with open("input") as f:
reader = csv.DictReader(f, delimiter=" ")
for line in reader:
print(line["Name"])
這假設“Steve”并不總是在字面上低于“Name”,因為如果其他列中的項目更長或更短,位置可能會有所不同,而是同一列中的項目。此外,這假定"Name"行將是文件中的第一行。
如果不是這種情況,并且如果Name可以出現在任何行中,并且您只想要其下方行中的名稱,則可以調用循環next使用的相同迭代器for:
import re
with open("input") as f:
for line in f: # note: no readlines!
if re.search(r'\bName\b', line): # \b == word boundary
pos = line.split().index("Name")
name = next(f).split()[pos]
print(name)

TA貢獻1797條經驗 獲得超4個贊
列表.txt:
zzzz zzzz zzzz Abcde
xxxx xxxx xxxx Name
zzzz zzzz zzzz Steve
zzzz zzzz zzzz Efghs
您可以將每一行拆分為一個空格,然后讀取感興趣的數組索引。
如下例:
logFile = "list.txt"
with open(logFile) as f:
lines = f.readlines()
for line in lines:
# split using space
result = line.split(" ")
# you can access the name directly:
# name = line.split(" ")[3]
# python array starts at 0
# so by using [3], you access the 4th column.
print result[3]
或者,您可以使用 numpy 僅打印數據字典中的第 4 列:
import numpy
logFile = "list.txt"
data = []
with open(logFile) as f:
lines = f.readlines()
for line in lines:
result = line.split(" ")
data.append(result)
matrix = numpy.matrix(data)
print matrix[:,[3]]

TA貢獻1872條經驗 獲得超4個贊
列表.txt:
zzzz zzzz zzzz Abcde
xxxx xxxx xxxx Name
zzzz zzzz zzzz Steve
zzzz zzzz zzzz Efghs
進而:
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
# flag for next line
nextLine = False
for line in content:
find_Name = line.find('Name') # check if Name exists in the line
if find_Name > 0 # If Name exists, set the next_line flag
nextLine = not nextLine
else:
if nextLine: # If the flag is set, grab the Name
print(line.split(" ")[-1]) # Grabbing the last word of the line
nextLine = not nextLine
輸出:
Steve
添加回答
舉報