【问题标题】:Sorting words in a text file (with parameters) and writing them into a new file with Python对文本文件中的单词(带参数)进行排序并使用 Python 将它们写入新文件
【发布时间】:2026-01-18 07:35:01
【问题描述】:

我有一个包含数千字的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])

有人可以为我指出正确的方向吗?现在他们没有按照他们应该的那样排序。

【问题讨论】:

  • 您的具体问题是什么?您希望代码完全做什么?相反会发生什么? (提供示例输入、所需输出和实际输出。包括完整的回溯(如果有))。见minimal reproducible example

标签: python string list file sorting


【解决方案1】:

这里有很多不清楚的地方,所以我会尽力清理这些。

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

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

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

【讨论】: