だから、私が書いているスクリプトに小さな問題があります。次のようなテキストファイルがあります。
'20 zebra 12 bear'
これは単なる例です。形式は、すべての項目がスペースで区切られた 1 行です。スクリプトはそれらを整理し、文字列に対して他のいくつかのことを行うように機能しますが、私が理解できないのは、それをそのままの状態に保つ方法です。たとえば、上記の行は次のように並べ替える必要があります。
12
bear
20
zebra
数字を数字の場所に、文字列を文字列の場所に保持する必要がありますが、それらは英数字順に並べ替える必要があります。これまでの私のスクリプトは次のとおりです。
#!/usr/bin/python
# Make sure you use the proper modules.
import sys, string
# This area defines the arguments and returns a usage message should it be used incorrectly.
try:
infilename = sys.argv[1]; outfilename = sys.argv[2]
except:
print "Usage:",sys.argv[0], "infile outfile"; sys.exit(1)
ifile = open(infilename, 'r') # Opens the input file for reading
ofile = open(outfilename, 'w') # Opens the output file for writing
data = ifile.readlines()[0].split() # Reads the lines on the input file
# The items in the list are sorted here and defined by a space.
sort = sorted(data, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
# Use this to remove any special characters in the list
filtered = [s.translate(None, string.punctuation) for s in sort]
ofile.write('\n'.join(filtered)) # Writes the final output to file (one on each line)
ifile.close() # Closes the input file
ofile.close() # Closes the output file
私はそれが最もきれいではないことを知っていますが、私はPythonを長く使用していないので、よりきれいにする方法について提案があれば、私はすべて聞いています. 私が本当に必要としているのは、数字を数字に、文字列を文字列に保ち、それらを入れ替えてソートすることだけです。与えられた援助に感謝します。