【发布时间】:2016-01-08 22:27:09
【问题描述】:
我有一个程序在 CSV 的第 1 列中随机生成一系列 5 个字母(ASCII,大写和小写),在同一 CSV 的第 2 列中随机生成 4 个数字 (0-9)。我可以按升序对第 2 列进行排序,但在第 1 列中遇到困难,因为它先对所有大写值进行排序,然后再对小写进行排序。这也会输出到一个新文件 sorted.csv。
例子:
ANcPI
DLBvA
FpSCo
beMhy
dWDjl
有谁知道如何对这些进行排序,以使大小写不会产生影响,而只是字母?它应该排序为:
ANcPI
beMhy
DLBvA
dWDjl
FpSCo
这是当前程序的代码:
import random
import string
#se='111411468' # Hardcoded value for development of the program
se = int(input('Please enter your ID for specific random number sequence: ')) # Asks user for ID number to generate files based on, uses se as above
random.seed(se,2) # Use of 2 in random.seed handles strings, numbers and others
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' # Uses all lower case ASCII
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Uses all upper case ASCII
ascii_letters = ascii_lowercase + ascii_uppercase # Combines all ASCII characters giving a higher degree of randomness to the generated files
digits = '0123456789' # Range of digit values for column 2 of 'unsorted.csv'
def rubbish_string(selection,l):
s = ''
for c in range(l):
s += selection[random.randint(0,len(selection)-1)]
return s
def writeRandomFile(filename):
with open(filename, 'w') as fout: # With automatically closes the file on finishing its extent,even with exceptions
fout.write('Personal ID,'+str(se)+'\n') # Write and assembled string, personal ID in grid A1 and personal ID No. in grid B1.....headings for the data
for xc in range(random.randint(10,20)):
fout.write(rubbish_string(ascii_letters,5)+','+rubbish_string(digits,4)+'\n') # Assemble and write a line to the file using 5 from the ascii_letters and 4 from the digits variable
def selectionSort (alist, col): # Slightly modified function for selection sort from part Q7A
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0 # Initally the maximum value is positioned at 0, Binary so position 1
for location in range(1, fillslot+1):
# Results in a list of size 2, first part is letters, second part is numbers
line1 = alist[location].split(",") # Makes sense to use "," for a .csv
line2 = alist[positionOfMax].split(",")
# Column-1 because computers count from zero (Binary)
# When the user enters 1 or 2, the computer deals with it in terms of 0 or 1
if line1[col - 1] > line2[col - 1]: # Deals with the Binary issue by taking 1 from the input column value from the user
positionOfMax=location
temp= alist[fillslot]
alist[fillslot]=alist[positionOfMax]
alist[positionOfMax]=temp
# Main part...
# Create random file based on the user data
writeRandomFile('unsorted.csv')
# Allow user pick which column to sort on, either 1 or 2 (could be adapted for more columns)
sortOnColumn = -1
while sortOnColumn != 1 and sortOnColumn != 2: # If the user does not enter an appropriate value, in this case 1 or 2 they are re-asked to input the column based on which ths sorting will be done.
sortOnColumn = int(input("Which column should the files be sorted on?"))
# Open unsorted file and load into a list
fin = open('unsorted.csv', 'r') # Opens a file for reading, called fin
data = [] # Creates an empty list named data
header = next(fin) # Skip first line because its Personal ID data, not random data generated by the program
for line in fin: # Loops through lines in fin
data.append(line.strip()) # Adds the line to the list, appending the list[]
selectionSort(data, sortOnColumn) # Sort list with the selection sort algorithm, calling the function, where data=the list and sortOnColum=user choice
# Write the now sorted list to a file, called fout
fout = open('sorted.csv', 'w') # Opening the empty sort.csv in write mode
fout.write(header) # Write PersonID data first at the top of the .csv as in the unsorted format
for entry in data: # Write ordered data
fout.write(entry)
data.sort(key=lambda m : m.lower()) # Sorts col.1 based on non case sensitive letters but issues with col.2..............
fout.write("\n") # Formating with "\n"
fout.close() # Close the file so not to have generated just a blank .csv with no data
print('Your Files Have Been Generated, Goodbye!')
【问题讨论】:
-
实际上,最好指出How to deal with case sensitive sorting for output files?,因为这是该问题的扩展版本,但包含可能更好的答案。
标签: python sorting python-3.x