如何阅读.txt文件以一种方式列出单词在Python中作为一个元素?



我的。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']

最新更新