为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哆啦的时光机 2022-08-16 18:58:33
我在实验室时遇到问题。我的任务是接收输入,根据空格拆分输入,并测试它是否在单独的列表中。我有一个函数,可以查看值是否在列表中,但是当我测试我知道在列表中的短语时,没有任何显示。我试图看看字符串拆分是如何拆分我的短语“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_corpuswhile 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
查看完整描述

3 回答

?
慕虎7371278

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


查看完整回答
反对 回复 2022-08-16
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

您没有分配拆分的结果 - 它不会就地发生。当您检查时,您只是在检查字符串的第 0 个元素 - 即 A。city_test[0]

替换为 以使功能符合您的期望。city_test.split(" ")city_test = city_test.split(" ")


查看完整回答
反对 回复 2022-08-16
?
噜噜哒

TA贡献1784条经验 获得超7个赞

使用city_test.split(“ ”) 时,您可以根据空格拆分字符串。但原来的city_test= [“austin is cool”] 保持不变。拆分后将列表存储在变量中。

list_name = city_test.split(“ ”)

您可以使用另一个变量名称而不是city_test,如果您希望原始列表存在,则可以存储它。


查看完整回答
反对 回复 2022-08-16
  • 3 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号