在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之间,我会将其(以及遵循该规则的所有其他行)排序到单独的列表中
答案 0 :(得分:1)
这完全符合您的需要(对于排序部分)
my_sorted_list = sorted(my_list, key=lambda line: int(line[0][1:-2]))
答案 1 :(得分:1)
使用元组作为键值:
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])
答案 2 :(得分:1)
怎么样:
# ---
# 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)