【问题标题】:reading from a file and checking if word in list从文件中读取并检查列表中的单词
【发布时间】:2019-04-24 04:10:46
【问题描述】:

我的妻子给我发了杂乱无章的长长的购物清单。我会将她的列表粘贴到一个文本文件中。我想编写一个程序,它将删除她的无序列表并将有序列表写入该文件。前任。所有水果在一起,肉在一起等。显然,该计划还处于起步阶段。在我的文本文件中,我写了:

banana
apple

在这种情况下,当我遍历文本文件的每一行时,我希望 item 被附加到水果中?但事实并非如此。我错过了什么?

fruit = []
vegetables = []
meat = []
dairy = []
fruit_list = ["banana", "apple", "orange"]

def read_list():
    with open("/storage/emulated/0/textfiles/grocery.txt", "r") as r:
        for item in r:
            if item in fruit_list:
                fruit.append(item)
    print(fruit)

【问题讨论】:

  • 剥离项目。最后有一个换行符。 "banana" != "banana\n"
  • 在比较前尽量去掉空格:item=item.strip()
  • String comparison doesn't seem to work for lines read from a file 的可能副本可能有更好的,但这是我得到的第一个。
  • 这样的迭代包括每个item中的换行符。尝试例如item.strip() 或使用 r.splitlines() 获取所有无换行项目的列表。

标签: python list for-loop conditional


【解决方案1】:

您需要从文件中删除行尾,因为它们在末尾带有\n\r\n(Windows 回车)。这意味着您将bananabanana\n 进行比较,它们 相等,导致没有附加任何内容。

您可以像这样预先使用str.strip() 来解决此问题:

item = item.strip()
if item in fruit_list:
    # rest of code

或者你可以用str.rstrip()从右边剥离:

item = item.rstrip()
if item in fruit_list:
    # rest of code

您还可以在使用 map() 进行迭代时剥离所有内容:

for item in map(str.strip, r):
    # rest of code

但前两种解决方案都很好。

【讨论】:

    【解决方案2】:

    使用.rstrip()从行尾剪切'\n'符号

    def read_list():
        with open("grocery.txt", "r") as r:
            for item in r:
                if item.rstrip() in fruit_list:
                    fruit.append(item)
        print(fruit)
    
    read_list()
    

    您也可以使用item.rstrip().lower() 来检查以大写字母开头的项目

    【讨论】:

    • Readlines 不需要,strip() 是他们问题的关键。
    • @SpghttCd readlines 将返回示例中第一行的 'banana\n'。而且它不等于fruit_list中的“香蕉”
    • 对,这正是问题所在。因此:readlines 不是问题的解决方案。
    猜你喜欢
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 2019-05-10
    • 2016-05-10
    • 2015-04-19
    • 2017-04-15
    • 2016-08-06
    相关资源
    最近更新 更多