3 回答

TA贡献1802条经验 获得超4个赞
您的代码中有一些错误。这是一个带有一些注释的固定版本:
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
再次阅读您的帖子,我注意到您使用“austin is cool”,就好像它是作为输入输入输入的一样。那么,您是否正在尝试检查输入的第一个单词是否是城市,或者输入的任何单词是否是城市?上面的代码处理后者。
另外,不要犹豫,使用额外的变量来保存结果。这样做可以使代码更易于阅读、跟踪和调试。您只需要确保在所有适当的位置使用该新变量即可。所以。。。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

TA贡献1802条经验 获得超6个赞
您没有分配拆分的结果 - 它不会就地发生。当您检查时,您只是在检查字符串的第 0 个元素 - 即 A。city_test[0]
替换为 以使功能符合您的期望。city_test.split(" ")
city_test = city_test.split(" ")

TA贡献1784条经验 获得超7个赞
使用city_test.split(“ ”) 时,您可以根据空格拆分字符串。但原来的city_test= [“austin is cool”] 保持不变。拆分后将列表存储在变量中。
list_name = city_test.split(“ ”)
您可以使用另一个变量名称而不是city_test,如果您希望原始列表存在,则可以存储它。
添加回答
举报