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条经验 获得超3个赞
列表.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
添加回答
举报