2014-12-14 7 views
0

Может кто-нибудь помочь? У меня есть файл, как это:Избавление от дубликатов

file = """he is a good man 
she is a beautiful woman 
this is a clever student 
he is a bad neighbour""" 

И я хочу отметить прилагательные в файле, так что я извлек их в списке, и я хочу, чтобы заменить их в исходном файле в другом формате, например, в скобках , Таким образом, список прилагательных выглядит следующим образом

ad = "good, bad, clever, beautiful," 

Я попытался это

for line in file.splitlines(): 
    for a in ad.split(','): 
     if a in line: 
      newline = line.replace(s, '[' + s + ']') 
      result = file.replace(line, newline) 
      print result 

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

he is a [good] man 
she is a beatiful woman 
this is a clever student 
he is a bad neighbor 

he is a good man 
she is a[ beatiful] woman 
this is a clever student 
he is a bad neighbor 

he is a good man 
she is a beatiful woman 
this is a[ clever] student 
he is a bad neighbor 

he is a good man 
she is a beatiful woman 
this is a clever student 
he is a[ bad] neighbor 

в то время как я ожидаю результат, как это

he is a [good] man 
she is a [beautiful] woman 
this is a [clever] student 
he is a [bad] neighbour 

ответ

0

Проблема в том, что вы r петля. Вы не расщепляете свои прилагательные, и разделенная линия не нужна, если вы собираетесь использовать замену. Таким образом, ваш код должен быть следующим:

adj = [word.strip() for word in ad.split(",") if word != ""] 
for a in adj: 
    if a in file: 
    file = file.replace(a, '[' + a + ']') 
print file 
Смежные вопросы