亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超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


查看完整回答
反對 回復 2021-10-26
  • 3 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號