3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的代碼中有一些錯(cuò)誤。這是一個(gè)帶有一些注釋的固定版本:
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”,就好像它是作為輸入輸入輸入的一樣。那么,您是否正在嘗試檢查輸入的第一個(gè)單詞是否是城市,或者輸入的任何單詞是否是城市?上面的代碼處理后者。
另外,不要猶豫,使用額外的變量來保存結(jié)果。這樣做可以使代碼更易于閱讀、跟蹤和調(diào)試。您只需要確保在所有適當(dāng)?shù)奈恢檬褂迷撔伦兞考纯?。所以。。。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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
您沒有分配拆分的結(jié)果 - 它不會(huì)就地發(fā)生。當(dāng)您檢查時(shí),您只是在檢查字符串的第 0 個(gè)元素 - 即 A。city_test[0]
替換為 以使功能符合您的期望。city_test.split(" ")
city_test = city_test.split(" ")

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用city_test.split(“ ”) 時(shí),您可以根據(jù)空格拆分字符串。但原來的city_test= [“austin is cool”] 保持不變。拆分后將列表存儲(chǔ)在變量中。
list_name = city_test.split(“ ”)
您可以使用另一個(gè)變量名稱而不是city_test,如果您希望原始列表存在,則可以存儲(chǔ)它。
添加回答
舉報(bào)