对文本文件中的单词进行排序(使用参数),并使用Python将其写入新文件

对文本文件中的单词进行排序(使用参数),并使用Python将其写入新文件,python,string,list,file,sorting,Python,String,List,File,Sorting,我有一个包含数千个单词的file.txt文件,我需要根据某些参数创建一个新文件,然后以某种方式对它们进行排序。 假设用户在测试时导入了正确的库,那么我的代码有什么问题?(有3个单独的功能) 首先,我必须创建一个包含特定字母的单词的文件,并按字典顺序对它们进行排序,然后将它们放入一个新的文件list.txt中 def getSortedContain(s,ifile,ofile): toWrite = "" toWrites = "" for line in ifile:

我有一个包含数千个单词的file.txt文件,我需要根据某些参数创建一个新文件,然后以某种方式对它们进行排序。 假设用户在测试时导入了正确的库,那么我的代码有什么问题?(有3个单独的功能)


首先,我必须创建一个包含特定字母的单词的文件,并按字典顺序对它们进行排序,然后将它们放入一个新的文件list.txt中

def getSortedContain(s,ifile,ofile):
  toWrite = ""
  toWrites = ""
  for line in ifile:
      word = line[:-1]
      if s in word:
        toWrite += word + "\n"
  newList = []
  newList.append(toWrite)
  newList.sort()
  for h in newList:
      toWrites += h
  ofile.write(toWrites[:-1])

第二个类似,但如果输入的字符串不在单词中,则必须按相反的词典顺序进行排序

def getReverseSortedNotContain(s,ifile,ofile):
  toWrite = ""
  toWrites = ""
  for line in ifile:
      word = line[:-1]
      if s not in word:
         toWrite += word + "\n"
  newList = []
  newList.append(toWrite)
  newList.sort()
  newList.reverse()
  for h in newList:
      toWrites += h
  ofile.write(toWrites[:-1])

对于第三个,我必须对包含一定数量整数的单词进行排序,并按每个单词的最后一个字符按字典顺序进行排序

def getRhymeSortedCount(n, ifile, ofile):
  toWrite = ""
  for line in ifile:
      word = line[:-1] #gets rid of \n
      if len(word) == n:
          toWrite += word + "\n"
  reversetoWrite = toWrite[::-1]
  newList = []
  newList.append(toWrite)
  newList.sort()
  newList.reverse()
  for h in newList:
      toWrites += h
  reversetoWrite = toWrites[::-1]
  ofile.write(reversetoWrites[:-1])

有人能给我指一下这些东西的正确方向吗?现在,他们没有按照预期进行排序。

这里有很多东西不清楚,所以我会尽力清理

将字符串连接到一个大字符串中,然后将该大字符串追加到列表中。然后,您尝试对单元素列表进行排序。这显然是无济于事的。而是将所有字符串放入一个列表中,然后对该列表进行排序

IE:对于第一个示例,请执行以下操作:

def getSortedContain(s,ifile,ofile):
  words = [word for word in ifile if s in words]
  words.sort()
  ofile.write("\n".join(words))

你的具体问题是什么?您希望代码具体做什么?会发生什么?(提供示例输入、期望输出和实际输出。包括完整的回溯(如果有)。看见