【问题标题】:Cannot append conditional result to new list无法将条件结果附加到新列表
【发布时间】:2019-02-11 05:38:33
【问题描述】:

我对 Python 或任何一般的编程语言都很陌生。

供参考:

  1. 作业
  2. 我的代码
  3. 问题

1.) 我的班级的作业是这样的:从文本文件“word.txt”中读取,并将符合条件的第一个文本文件中的单词写入一个新的文本文件。 例如,如果函数是getListEnd('s', 'word.txt', 'word1.txt') 并且条件是ofile中的单词必须都以字符's'结尾,那么我的ifile word.txt =[apples,carrots, cheese, mustard, questions] 会被分类到一个外文 word1.txt=[apples,carrots, questions]

2.) 这是我的代码:

mf1 = open("/Users/XXXX/word.txt", "r")
mf2 = open("/Users/XXXX/word2.txt", "w+")
mylist1=[]                            #list for storing word.txt strings
mylist2=[]                            #list for storing sorted strings

def sort(c):                          #function for sorting mylist1 for 
    for i in mylist1:                        criteria into my list2       
        if c==i[-1]:
            mylist2.append(i)

def getListEnd(c, ifile, ofile):
    for s in mf1:                      #loop for appending word.txt to list 1
        mylist1.append(s)                   
    print(len(mylist1))                #check if mylist1 contains word.txt
    sort(c)                            #append sorted words to list2
    with open('word2.txt', 'w+') as mf2:   #write into word1.txt list2
        for listitem in mylist2:
            mf2.write('%s\n' % listitem)

getListEnd('s', 'word.txt', 'word2.txt')

3.) 所以问题是:为什么每当我尝试将已排序的单词附加到 mylist2 时,什么都没有发生?也就是说,当我检查 mylist2 的长度时,它显示为 0,即使 word.txt 文件中有很多以 s 结尾的单词?我知道在检查 myList1 是否有以最后一个字母 's' 结尾的字符时出错,但我不知道是什么,我无法将其附加到 mylist2。

【问题讨论】:

  • 您能否详细说明您的第二条评论@John Gordon?我不确定这到底是什么意思,但是当我尝试编写文件 word2.txt 时它仍然是空的,因为 mylist2 中没有任何内容,所以我想你可能有一个解决方案。
  • 查看我的更新答案。

标签: python list file append


【解决方案1】:

你的程序有两个问题:

  1. 您在对输入进行排序之前写入输出文件
  2. 您在字符串中包含换行符,因此当您比较最后一个字符时,您实际上是在比较换行符。

这是您与 cmets 有关更改的程序:

# mf1 = open("word.txt", "r")      # Don't do this here. You read it in in your with block anyway.
# mf2 = open("word2.txt", "w+").   # Don't do this here. You write it in your with block anyway
mylist1=[]
mylist2=[]

def sort(c):
    for i in mylist1:
        if c==i[-1]:
            mylist2.append(i)

def getListEnd(c, ifile):
    with open(ifile, "r") as mf1:
        for s in mf1:  # the strings will still contain the newlines if read this way
                       # so when you check the end of the string you'll actually be comparing
                       # a newline character.
            if "\n" in s:
                mylist1.append(s[:-1]) # if there's a newline character, 
                                       # don't include it when appending to the list
            else:
                mylist1.append(s)
        print("mylist length: ", len(mylist1))
        print("mylist1: ", mylist1)
        sort(c)

getListEnd('s', 'word.txt') # you don't need to pass it any info about the output file
print("mylist2: ", mylist2)

## Your writing block has to come after you've sorted it! Not before
with open('word2.txt', 'w+') as mf2:
    for listitem in mylist2:
        mf2.write('%s\n' % listitem)

更一般地说:

要创建一个仅包含以字母“s”结尾的项目的列表,您可以这样做:

input_list = ['apples', 'carrot', 'johns', 'list']
output = [i for i in input_list if "s" == i[-1]]

print(output)
>> ['apples', 'johns']

output = [i for i in input_list if "s" == i[-1] 行正在使用i 遍历您的input_list 列表并检查每个项目以查看每个字符串i[-1] 的最后一个字符是否是字符's'。然后它返回一个包含所有符合条件的项目的列表。一种更具表现力的编码方式是:

for word in input_list:
    if word[-1] == "s":
        output.append(word)

随着文件的读取和写入,在 python 中在 with 运算符中执行它们会更安全,因为它可以确保您没有未关闭的文件挂在周围/更安全的范围。

更简单的版本:

这是一个玩具程序,我认为它可以满足您的需求:

with open("word.txt", "r") as f:
    mylist1 = f.read().split("\n") # splits the input file around newlines

mylist2 = [i for i in mylist1 if "s" == i[-1]] 

with open("word2.txt", "w") as f:
    for word in mylist2:
        f.write(f"{word}\n") # writes word into the file

如果 word.txt 是:

john
apples
carrots
lewis

那么word2.txt就变成了:

apples
carrots
lewis

【讨论】:

  • 感谢您的广泛回答。我尝试实施您的解决方案,它帮助我理解了作业的写作方面,但是我仍然遇到 mylist2 中没有附加任何内容的问题,因此 word2.txt 仍然为空
  • 您是否准确地复制了我的代码?它适用于我的电脑。您需要将代码粘贴到某个地方,以便我评论出了什么问题。
  • 我刚刚更新了我的代码以与您的文件命名保持一致。
  • 关于您的几个示例中的条件if "s" is i[-1]:您不应该将字符串与is 进行比较。虽然由于“字符串实习”,它可能适用于 cpython 中的大多数情况,但它可能并不总是有效。此外,它是特定于实现的行为。其他解释器可以(并且可能确实)以各种不同的方式处理字符串,因此更容易得到不引用同一对象的相等字符串。当您关心的是同等价值而不是身份时,请始终使用==
  • 哇!!问题解决了!我没有意识到这个问题与写作块有关,但你的代码确实成功了!非常感谢,我想我更了解如何使用 python 读写文件了!
【解决方案2】:

这是一个例子:

with open('words1.txt', 'w') as f_object:
       f_object.write("Apples" + "\n")
       f_object.write("Rubles" + "\n")
       f_object.write("Nope" + "\n")
       f_object.write("Nah" + "\n")
       f_object.write("Georges" + "\n")


f_object.close()
print("Done")

with open('words1.txt', 'r') as f:
lines = f.readlines()


with open('words2.txt', 'w') as f_ob:
     for line in lines:
        line = line.rstrip()
        if line[-1] == 's':
             f_ob.write(line + '\n')

print("Done")

我们可以简单地设置一个条件,如果单词以's'结尾,我们会将它添加到新的.txt 文件中。例如,当我们遍历每一行时,我们可以获取字符串中的最后一个索引。 “如果”该行的最后一个索引等于 s,那么我们显然可以将该行写入文件。如果没有,它将跳过。您的 words2.txt 文件中的输出将是:

Apples
Rubles
Georges

【讨论】:

    【解决方案3】:

    使用for x in file 循环从文件中读取行会在每行的末尾为您提供一个换行符。

    所以,i[-1] 是换行符,而不是单词的最后一个字母。

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 1970-01-01
      • 2017-03-28
      • 2021-06-07
      • 2022-10-24
      • 2012-03-10
      • 1970-01-01
      • 2013-09-25
      • 2021-01-11
      相关资源
      最近更新 更多