2016-11-09 65 views
0

我有這樣的代碼,我打的是純文本格式閱讀Python - 閱讀和行間打印?

Python文件:

from itertools import islice 

def phones(): 
    with open('phones.txt','r+') as f: 
     lines = islice(f, 2, 4) #lines 2 and 4 only 
     for line in f: 
      found_phone = line.find('Phone') 
      if found_phone != -1: 
       Phones = line[found_phone+len('Phone:'):] 
       print Phones 
    return Phones 

phones() 

我的問題是我想打印線2和4之間旁邊的「手機」這個詞, 它打印的每一個字我只想要2線和4

之間經過「手機」這是我的文本文件

First lines of Phones 
     Phone Blackberry #Line 2 
     Phone iPhone  #Line 3 
     Phone Huawei  #Line 4 
Second lines of Phones 
     Phone Samsung 
     Phone LG 

氏s是我的輸出:

enter image description here

我想只打印是線2和4 之間,我想這樣的輸出:

Blackberry 
iPhone 
Huawei 

我試圖用itertools做到這一點,但它不工作... 我在做什麼錯了?

+1

'在F'行着眼於文件中的每一行。我認爲'爲了排隊'可能是你想要做的。 – asongtoruin

+0

你也可以使用'startwith' https://docs.python.org/2/library/stdtypes.html#str.startswith,所以你不需要splice + find。 –

回答

0

這裏有兩個問題。首先,你指定lines作爲切片,但是接着遍歷整個文件,f。其次,你的切片不會返回你之後的內容 - islice似乎是基於零的,並且不會包含上限(來自我在Python 2.7中的測試),因此實際上後面的部分是islice(f, 1, 4)

的代碼與這些校正是如下:

from itertools import islice 

def phones(): 
    with open('phones.txt','r+') as f: 
     lines = islice(f, 1, 4) 
     for line in lines: 
      found_phone = line.find('Phone') 
      if found_phone != -1: 
       Phones = line[found_phone+len('Phone:'):] 
       print Phones 
    return Phones 

phones() 

這返回

Blackberry 

iPhone 

Huawei 

要刪除的值之間的線,可以使用print Phones.rstrip()而非print Phones

0

你可以試試這個:

lines = [line.split() for line in open('phones.txt','r+')] 
lines = lines [1:4] 

select = [x[1] for x in lines ] 

輸出=> [ '黑莓', 'iPhone', '華爲']