Re: [問題] 關於List的問題

看板Python作者 (Apua)時間14年前 (2011/09/17 19:56), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/3 (看更多)
※ 引述《blackboy (黑男孩)》之銘言: : 後來有想過用regular search的方式去判定該行是否有符合我需要的關鍵字,不過這樣 : 我需要改成用迴圈把list的每一行讀出來後再用regular來比對。因為我不知道怎麼判 : 定迴圈已經讀到該List的最後一行。 其實你不用思考迴圈是否讀到最後一行,參考以下例子:: for line in open("FILE"): print line, : 我原本的想法是假設迴圈已經比對過List所有的字串後,沒有找到我需要的關鍵字才 : 把整個List清空,不知道是否有比較好的解法來處理這個問題呢? 我看到你的code裡有 `regex2` 這東西,不知道是不是自己寫的? 建議用標準模組 `re` 來做regexp搜尋,各種功能都能輕易做到 : 我的Log類似像是底下這樣: : Tag : str1 : str2 : str3 : Tag : str4 : str5 : str6 : Tag 如果用 `re` 模組為例子: >>> log 'Tag\nstr1\nstr2\nstr3\nTag\nstr4\nstr5\nstr6\nTag' >>> >>> import re >>> >>> m = re.search( '(?<=Tag\n).*?(?=Tag)' , log , re.S ) # a match object >>> m.group(0) 'str1\nstr2\nstr3\n' >>> >>> m = re.findall( '(?<=Tag\n).*?(?=Tag)' , log , re.S ) # a list of string object >>> m ['str1\nstr2\nstr3\n', 'str4\nstr5\nstr6\n'] >>> >>> for m in re.finditer( '(?<=Tag\n).*?(?=Tag)' , log , re.S ): ... print m.group(0) # m is a match object ... str1 str2 str3 str4 str5 str6 : 每個段落間會有固定的tag字串做為分隔,但是其中的字串行數不確定,我原先的做法 : 是先將全部的內容讀入一個List內,然後用迴圈一句一句讀出來,如果遇到兩個Tag包 : 起來的時候,就把裡面的內容去filter,如果其中有一段是符合我的關鍵字,那麼我就 : 把這整段放到另一個List裡面。 : 如果是用if str in list的方式,必須是完全符合那字串才會丟到另一個List內。 : 可是我有些關鍵字可能是在該行字串的其中一部分,那我就想說改用Regular的方式來 : 做filter。 事實上我不清楚你還想對撈出來的「區塊」做什麼處理,但我相信regexp較直覺 re module的docs : http://docs.python.org/library/re.html 我強烈建議你注意7.2.1. 那段中 `(?<=...)` 的用法說明 還有7.2.3. 那段中對各種tag的用法說明 Python的re強的很恐怖.... : Code大約像是這樣,這是我一開始的寫法。 : try: : while True: : line = fp.next() : if regex2.search(line) and len(Error0) != 0: //抓到第一個tag : for line in check: //check是我要篩選的關鍵字 : if line in Error0: : content = content[:]+Error0[:] : Error0 = [] : getContent = 0 : else: : Error0 = [] : getContent = 0 這邊可以寫成這樣:: for line in check: #其實我懷疑你line和check寫顛倒了 if line in Error0: content += Error0 Error0, getContent = [], 0 : elif regex2.search(line) and len(Error0) == 0: : getContent = 1 : elif not regex2.search(line) and getContent == 1: : Error0.append(line) : except StopIteration: : pass (實際上我看不太懂這段程式碼在做什麼....orz) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 112.104.13.57
文章代碼(AID): #1ET8i4ka (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 3 篇):
文章代碼(AID): #1ET8i4ka (Python)