为了账号安全,请及时绑定邮箱和手机立即绑定

Python:如何解析下一行?

Python:如何解析下一行?

肥皂起泡泡 2021-10-26 18:14:00
我对 Python 没有那么丰富的经验,因此我请求帮助我改进我的代码。我正在尝试解析“名称”字段下的“史蒂夫”:xxxx xxxx xxxx Namezzzz 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 exampleName =Steve任何帮助表示赞赏。
查看完整描述

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)


查看完整回答
反对 回复 2021-10-26
?
繁星coding

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]]


查看完整回答
反对 回复 2021-10-26
?
守着一只汪

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


查看完整回答
反对 回复 2021-10-26
  • 3 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号