2016-11-09 128 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', '华为']