В вашем коде есть несколько ошибок. Вот исправленная версия с некоторыми комментариями:
def load_city_corpus():
city_list = []
filename = "NYC2-cities.txt"
# return ['austin', 'boston'] # my stub for testing...
with open(filename) as f:
for line in f:
city_list.append(line.strip()) # could add lower() for safety...
return city_list
def is_a_city(city, city_list):
try:
index = city_list.index(city) # could be city.lower() for safety
return True
except ValueError: # AttributeError:
return False
list_of_cities = load_city_corpus() # Need the () to call the func
while True:
city_test = input("Enter some text (or ENTER to quit): ")
if city_test == "":
break
city_test = city_test.split() # (" ") not an error to use, but not nec.
# ^^^^^^^^^^ have to assign the result of the split to preserve it...
print(city_test[0]) #prints "a" -- not anymore! :)
for item in city_test:
if is_a_city(item, list_of_cities) == True: # item, not city_test
print(f"{item.title()} is a city") # item, not city_test
# get rid of the below, because it will always break out of the loop after one pass.
# else:
# break
Читая ваш пост снова, я замечаю, что вы используете «Остин круто», как если бы он был введен в качестве ввода. Итак, вы пытаетесь проверить, является ли первое слово ввода городом, или любое слово ввода города? Приведенный выше код обрабатывает последнее.
Кроме того, не стесняйтесь использовать дополнительную переменную для хранения результатов city_test.split()
. Это может облегчить чтение, отслеживание и отладку кода. Вам просто нужно использовать эту новую переменную во всех нужных местах. Итак ...
city_splits = city_test.split()
print(city_splits[0]) #prints "a" -- not anymore! :)
for item in city_splits:
if is_a_city(item, list_of_cities) == True: # item, not city_test
print(f"{item.title()} is a city") # item, not city_test