在python中拆分一个字符串,然后将每个单独的部分与一个值列表进行比较时会遇到麻烦

在python中拆分一个字符串,然后将每个单独的部分与一个值列表进行比较时会遇到麻烦,python,string,Python,String,我在实验室遇到了麻烦。我的任务是接收输入,根据空格分割输入,并测试它是否在一个单独的列表中。我有一个函数,可以查看值是否在列表中,但是当我测试一个我知道在列表中的短语时,什么都没有显示。我试图查看字符串拆分是如何拆分我的短语“austin is cool”的,当我输入city[0]时,它只返回一个“a”。我还创建了一些函数,这些函数通过一个txt文件进行解析,并创建了一个列表,这样我就可以与另一个函数进行比较,并实际检查单词是否位于列表中。以下是我的最终程序+功能: def load_city_

我在实验室遇到了麻烦。我的任务是接收输入,根据空格分割输入,并测试它是否在一个单独的列表中。我有一个函数,可以查看值是否在列表中,但是当我测试一个我知道在列表中的短语时,什么都没有显示。我试图查看字符串拆分是如何拆分我的短语“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
\\\\\

\\\\\


您没有指定拆分的结果-拆分没有发生在适当的位置。当您选中城市测试[0]时,您只需检查字符串的第0个元素,即A

city\u test.split(“”)替换为
city\u test=city\u test.split(“”)以使功能符合您的期望。

在使用city\u test.split(“”)时,您可以基于空格拆分字符串。但最初的城市测试=[“奥斯汀很酷”]保持不变。拆分后将列表存储在变量中

列表\名称=城市\测试。拆分(“”)


您可以使用另一个变量名而不是city_test,如果您希望原始列表出现,可以将其存储。

您的代码中有一些错误。下面是一个带有一些注释的固定版本:

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\u 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

值得注意的是,该代码中还有一些其他错误,因此您可能希望对其进行另一次通读!非常感谢你,这绝对有帮助!是的,我想通过解析字符串来检测整个字符串中任何地方的城市,我只是用“Austin很酷”作为一种测试方法。再次感谢你的帮助!
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_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