简体   繁体   English

无法将条件结果附加到新列表

[英]Cannot append conditional result to new list

I'm very new to Python or any programming language in general. 我对Python或一般任何编程语言都是新手。

For reference: 以供参考:

  1. Assignment 分配
  2. My Code 我的密码
  3. Question

1.) The assignment for my class is this: read from text file 'word.txt' and write into a new text file the words from the first text file that fit the criteria. 1.)我班的作业是这样的:从文本文件'word.txt'中读取,并将符合条件的第一个文本文件中的单词写入新的文本文件中。 For example, if the function is getListEnd('s', 'word.txt', 'word1.txt') and the criteria is that the words in the ofile must all end with the character 's' then my ifile word.txt=[apples, carrots, cheese, mustard, problems] would be sorted into an ofile word1.txt=[apples, carrots, problems] 例如,如果函数为getListEnd('s','word.txt','word1.txt'),并且条件是该公墓中的单词必须全部以字符's'结尾,则我的ifile word.txt = [苹果,胡萝卜,奶酪,芥末,问题]将被分类为普通单词1.txt = [苹果,胡萝卜,问题]

2.) Here is my code: 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.) So the question is: why is it that whenever I try to append into mylist2 the sorted words nothing happens? 3.)问题是:为什么为什么每次尝试将mysort2后面的单词排序都没有发生? That is, when I check the length of mylist2 it says 0 even though there are many words in the word.txt file that end in s? 也就是说,当我检查mylist2的长度时,即使在word.txt文件中有很多以s结尾的单词,它也显示为0? I know that there is an error in checking myList1 for characters that end with the last letter 's' but I don't know what and I can't get it to append to mylist2. 我知道在检查myList1中是否存在以最后一个字母's'结尾的字符时出错,但我不知道该怎么办,也无法将其追加到mylist2中。

There are two things wrong with your program: 您的程序有两点错误:

  1. You were writing to the output file before you had sorted the input 在对输入进行排序之前,您正在写入输出文件
  2. You were including newlines in your string so when you compared the last character you were actually comparing newlines. 您在字符串中包含换行符,因此当您比较最后一个字符时,实际上是在比较换行符。

Here's your program with comments about the changes: 这是您的程序,其中包含有关更改的注释:

# 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)

More generally: 更普遍:

To create a list with only items that end in the letter "s" you can simply do: 要创建仅包含以字母“ s”结尾的项目的列表,您可以执行以下操作:

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

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

The line output = [i for i in input_list if "s" == i[-1] is iterating through your input_list list with i and checking each item to see if the last character of each string i[-1] is the character 's' . 该生产线output = [i for i in input_list if "s" == i[-1]通过您的迭代input_list清单, i和检查每个项目,看是否每个字符串的最后一个字符i[-1]是字符's' It then returns a list with all the items that match the condition. 然后,它返回一个列表,其中包含与条件匹配的所有项目。 A more expressive way to code it would be: 一种更具表现力的编码方式是:

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

With the reading and writing of files it's safer in python to do them within with operators as it ensures that you don't have un-closed files hanging around/is safer scope wise. 通过读取和写入文件,使用python在操作员内部with更加安全,因为这可以确保您没有未关闭的文件挂在周围,或者在范围上更安全。

A simpler version: 一个简单的版本:

Here's a toy program that I think does what you want: 我认为这是一个玩具程序,可以满足您的需求:

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

if word.txt was: 如果word.txt是:

john
apples
carrots
lewis

Then word2.txt becomes: 然后word2.txt变成:

apples
carrots
lewis

Reading lines from a file with a for x in file loop gives you a newline character at the end of each line. 使用文件中的for x in file循环从文件中读取行,可以在每一行的末尾提供换行符。

So, i[-1] is the newline character, not the last letter of the word. 因此, i[-1]是换行符,而不是单词的最后一个字母。

Here is an example: 这是一个例子:

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")

We can simply make a condition that if the word ends in 's' we will add it to the new .txt file. 我们可以简单地做出一个条件,即如果单词以's'结尾,我们将其添加到新的.txt文件中。 We can grab the last index in the string for example as we iterate through each line. 例如,当我们遍历每一行时,我们可以获取字符串中的最后一个索引。 "if" the last index of the line is equal to s, then we can obviously write the line to the file. “如果”该行的最后一个索引等于s,那么我们显然可以将该行写入文件。 If not it will skip. 如果没有,它将跳过。 The output in your words2.txt file will be: 您的words2.txt文件中的输出将为:

Apples
Rubles
Georges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM