2015-04-26 3 views
0

У меня есть этот код:открытие с дубликатами

chain = '>' 
 
contain='' 
 

 
file = raw_input('Enter your filename : ') 
 

 

 
fileName = open(file,'r') 
 
for line in fileName: 
 
\t if chain in line : 
 
\t \t pass 
 
\t \t \t 
 
\t if not(chain in line): 
 
\t \t contain+=line 
 
\t \t print contain 
 
\t \t 
 

 
fileName.close()

и этот file.txt:

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management. 
He has a large and comprehensive standard library 

Я получил этот результат для "печати":

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management. 

Python supports multiple programming paradigms, including object-oriented, imperative and functional programming. 
It features a dynamic type system and automatic memory management. 
He has a large and comprehensive standard library 

Почему у меня есть дубликаты?

+0

Цепочка может быть только в линии или нет, ваши два ifs избыточны –

+0

да. Я буду как больше условий позже – yokie

ответ

0

В каждой итерации цикла, когда:

if not(chain in line): 
    contain+=line 
    print(contain) 

, так как вы конкатенация каждой строки в contain, при печати, он покажет вам первый sentece из первой итерации, то первый + вторых предложений на второй итерации и т. д. Следовательно, дублирование.

Замена print(contain)print(line) будет печатать линии без дублирования.

0

После первой итерации вы добавляете первую строку своего файла в contain, а затем печатаете ее.

После второй итерации вы добавляете вторую строку своего файла в contain, которая по-прежнему содержит первую строку, а затем печатает ее.

То же самое происходит и для третьей итерации.

Вы видите дубликаты, потому что вы печатаете contain несколько раз, и в нем есть предыдущие строки.

+0

да .. конечно !!!! :( – yokie

Смежные вопросы