在Python中,我正在读取一个包含许多行的大文件。每行包含一个数字,然后是一个字符串,如下所示:
[37273738] Hello world!
[83847273747] Hey my name is James!以此类推。
在读取txt文件并将其放入列表后,我想知道如何提取数字,然后根据数字对整行代码进行排序?
file = open("info.txt","r")
myList = []
for line in file:
line = line.split()
myList.append(line)我想做的是:
由于消息1中的数字介于37273700和38000000之间,因此我将把它(以及遵循该规则的所有其他行)排序到一个单独的列表中
发布于 2015-11-18 05:28:20
这正是您所需要的(对于排序部分)
my_sorted_list = sorted(my_list, key=lambda line: int(line[0][1:-2]))发布于 2015-11-18 05:47:58
使用元组作为键值:
for line in file:
line = line.split()
keyval = (line[0].replace('[','').replace(']',''),line[1:])
print(keyval)
myList.append(keyval)排序
my_sorted_list = sorted(myList, key=lambda line: line[0])发布于 2015-11-18 05:52:03
这样如何:
# ---
# Function which gets a number from a line like so:
# - searches for the pattern: start_of_line, [, sequence of digits
# - if that's not found (e.g. empty line) return 0
# - if it is found, try to convert it to a number type
# - return the number, or 0 if that conversion fails
def extract_number(line):
import re
search_result = re.findall('^\[(\d+)\]', line)
if not search_result:
num = 0
else:
try:
num = int(search_result[0])
except ValueError:
num = 0
return num
# ---
# Read all the lines into a list
with open("info.txt") as f:
lines = f.readlines()
# Sort them using the number function above, and print them
lines = sorted(lines, key=extract_number)
print ''.join(lines)它在没有数字的行的情况下更具弹性,如果数字可能出现在不同的位置(例如,行开头的空格),则更具可调性。
(强制建议不要使用file作为变量名,因为它已经是一个内置函数名,这会让人感到困惑)。
现在有了一个extract_number()函数,它更容易过滤:
lines2 = [L for L in lines if 37273700 < extract_number(L) < 38000000]
print ''.join(lines2)https://stackoverflow.com/questions/33767208
复制相似问题