【发布时间】: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