我的。txt文件是这样的:
9/30/19 [Jamba Juice] $5
10/7/19 [Target] $17
我如何将其转换为python中的列表,使"Jamba Juice"
保持为一个元素?如果我用.split(" ")
,"Jamba"
和"Juice"
就变成了列表中的两个元素。我不能使用re
库。
with open(INPUT_FILE) as bills_file:
for line in bills_file:
line = line.strip()
parts = line.split(" ")
既然您知道分隔线的第一个元素是日期,最后一个元素是美元金额,那么只需将分隔线的其余元素连接起来:
with open(INPUT_FILE) as bills_file:
for line in bills_file:
line = line.strip()
parts = line.split(" ")
date = parts[0]
cost = parts[-1]
name = " ".join(parts[1:-1]) # parts[1:-1] selects the first through second-last elements of parts, then we join them with spaces
parts = [date, name[1:-1], cost] # name[1:-1] selects the fist through second-last characters of name, which removes the brackets
print(parts)
输出:
['9/30/19', 'Jamba Juice', '$5']
['10/7/19', 'Target', '$17']