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

2024-09-30 16:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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


首先,我必须创建一个包含特定字母的单词的文件,并按字典顺序对它们进行排序,然后将它们放入一个新文件中列表.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])

有人能给我指出正确的方向吗?现在他们没有按他们应该的那样分类。你知道吗


Tags: 文件infor字典排序顺序defline
1条回答
网友
1楼 · 发布于 2024-09-30 16:26:01

这里有很多不清楚的东西,所以我会尽力清理。你知道吗

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

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

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

相关问题 更多 >