2015-11-17 4 views
0

Я пытаюсь сортировать сообщения из craigslist, но кодирование мешает мне.Не удается успешно сравнить строки с python

Вот код

# -*- coding: utf-8 -*- 

sort_list = ['position title: construction laborer position summary: assisting on construction site with cleanup and other general labor. previous construction experience is preferred. safety conscious is a must! essential duties and responsibilities ● general site cleanup','i\'m moving a small church organ about 3 miles from west linn to oregon city monday morning. i need to a service to move it. it is being moved from the first level in one house to a first level in another house. it\'s about the size of but definitely lighter than a smaller upright piano. i would need it movedand monday morning at about 9 a.m. please email me your quote thank you ','position title: cdl a driver position summary: local moving company looking for a class a cdl driver to operate a 53 ft tractor‐trailer. only candidates willing to assist with local and commercial moves will be considered. this is a local driving job, drivers are home every night. essential duties and responsibilities: ● safely navigate moving trucks between city and residential neighborhoods. ● steady year round work. '] 


## List of stuff we don't want 
list = ['CDL','Full Time','Part Time','Drivers','Salary','Background Check','Resume','valid drivers license','social security','career','Full-Time','part-time'] 

for content in sort_list: 
    content = content.lower() 
    for thing in list: 
     thing = thing.lower() 
     if thing in content: 
      outcome = False 
     elif thing not in content: 
      outcome = True 

    print "\n\n",outcome,"\n\n",content 

Они все вышли, как True. Они явно не должны. Только два должны быть истинными.

Редактировать: Просто осознал, что может быть так, как я обрабатываю цикл. Как мне сделать это с результатом, который я хочу?

ответ

2

Чтобы просто получить одно значение за content вам необходимо установить начальное значение для booleanflag перед тем итерация за все в content; если вы ловите вещь, которая существует в нем, вы измените значение flag и вырваться из цикла:

for content in sort_list: 
    flag = True 
    content = content.lower() 
    for thing in list1: 
     thing = thing.lower() 
     if thing in content: 
      flag = False 
      break 
    if flag: 
     print ("\n\n",outcome,"\n\n",content) 

который теперь дает:

True 

position title: construction laborer position summary: assisting on construction site with cleanup and other general labor. previous construction experience is preferred. safety conscious is a must! essential duties and responsibilities ● general site cleanup 


True 

i'm moving a small church organ about 3 miles from west linn to oregon city monday morning. i need to a service to move it. it is being moved from the first level in one house to a first level in another house. it's about the size of but definitely lighter than a smaller upright piano. i would need it movedand monday morning at about 9 a.m. please email me your quote thank you 

Кроме того, вы не должны использовать имена как list для вашего list, потому что он маскирует встроенный тип list. Вместо этого используйте что-то немного другое, но в равной степени выразительное, например list1, my_list и так далее.

+0

Хорошо, но я все еще смущен. Можете ли вы, пожалуйста, показать мне, как я получу один твердый True или False из этого, вместо того, чтобы получить гигантский список правды и ложных? – Manix

1

переменная outcome должна быть инициализирована вне цикла for. Вот упрощенный код

for content in sort_list: 
    content = content.lower() 
    outcome = True 
    for thing in list: 
     thing = thing.lower() 
     if thing in content: 
      outcome = False 
Смежные вопросы