猿问

在python中拆分字符串,然后将每个单独的部分与值列表进行比较时出现问题

我在实验室时遇到问题。我的任务是接收输入,根据空格拆分输入,并测试它是否在单独的列表中。我有一个函数,可以查看值是否在列表中,但是当我测试我知道在列表中的短语时,没有任何显示。我试图看看字符串拆分是如何拆分我的短语“austin is cool”的,当我输入city[0]时,它只返回了一个“a”。我还创建了通过txt文件解析的函数,并创建了一个列表,以便我可以进行比较,另一个函数实际上检查该单词是否位于列表中。以下是我最后的程序+函数:


def load_city_corpus():

    city_list = []

    filename = "NYC2-cities.txt"

    with open(filename) as f:

        for line in f:

            city_list.append(line.strip())

    return city_list

\\\\\


def is_a_city(city,city_list):

    try:

        index = city_list.index(city)

        return True

    except AttributeError:

        return False

\\\\\


list_of_cities = load_city_corpus

while True:

   city_test = input("Enter some text (or ENTER to quit):")

   if city_test == "":

      break

   city_test.split(" ")

   print(city_test[0]) #prints "a"

   for item in city_test:

      if is_a_city(city_test,list_of_cities) == True:

          print(f"{city_test.title()} is a city")

   else:

      break


哆啦的时光机
浏览 116回答 3
3回答

慕虎7371278

您的代码中有一些错误。这是一个带有一些注释的固定版本: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_listdef is_a_city(city, city_list):    try:        index = city_list.index(city) # could be city.lower() for safety        return True    except ValueError: # AttributeError:        return Falselist_of_cities = load_city_corpus() # Need the () to call the funcwhile 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

呼啦一阵风

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

噜噜哒

使用city_test.split(“ ”) 时,您可以根据空格拆分字符串。但原来的city_test= [“austin is cool”] 保持不变。拆分后将列表存储在变量中。list_name = city_test.split(“ ”)您可以使用另一个变量名称而不是city_test,如果您希望原始列表存在,则可以存储它。
随时随地看视频慕课网APP

相关分类

Python
我要回答