Python:如何解析下一行?

我对 Python 没有那么丰富的经验,因此我请求帮助我改进我的代码。


我正在尝试解析“名称”字段下的“史蒂夫”:


xxxx xxxx xxxx Name

zzzz zzzz zzzz Steve

我的代码是这样的:


for line in myfile.readlines():

    [..]

    if re.search(r'Name =', line):

        print("Destination = ")

        samples+=line[15:19]

        nextline = "y"

    if nextline == 'y':

        samples+=line[15:19]

最终我将打印所有内容:


[..]    

for s in samples:

   myfile2.write(s)

它确实有效,但我不敢相信没有更聪明的方法可以做到这一点(比如在满足条件后访问以下行......)。


这是我需要解析的文件的示例。但结构可能会有所不同,例如


#This is another example

Name =

Steve

任何帮助表示赞赏。


肥皂起泡泡
浏览 167回答 3
3回答

千巷猫影

不要重新发明轮子。使用csv模块,例如DictReader:import csvwith open("input") as f:    reader = csv.DictReader(f, delimiter=" ")    for line in reader:        print(line["Name"])这假设“Steve”并不总是在字面上低于“Name”,因为如果其他列中的项目更长或更短,位置可能会有所不同,而是同一列中的项目。此外,这假定"Name"行将是文件中的第一行。如果不是这种情况,并且如果Name可以出现在任何行中,并且您只想要其下方行中的名称,则可以调用循环next使用的相同迭代器for:import rewith 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)

繁星coding

列表.txt:zzzz zzzz zzzz Abcdexxxx xxxx xxxx Namezzzz zzzz zzzz Stevezzzz 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 numpylogFile = "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]]

守着一只汪

列表.txt:zzzz zzzz zzzz Abcdexxxx xxxx xxxx Namezzzz zzzz zzzz Stevezzzz zzzz zzzz Efghs进而:logFile = "list.txt"with open(logFile) as f:    content = f.readlines()    # you may also want to remove empty linescontent = [l.strip() for l in content if l.strip()]# flag for next linenextLine = Falsefor 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python