如何将一行中没有括号和逗号的文本转储到 Pickle 文件中
How to dump text on one line without brackets and commas into Pickle file
我正在编写一个货币转换器,其中一个部分是一个程序,它允许您检查和更改英镑与其他三种货币之间的转换率。虽然实际转换很好,但我在将新汇率导出到单行 pickle 文件时遇到了问题。这是因为,费率以以下格式写入 pickle 文件中:
英镑兑 1 欧元 1.15 美元 1.3 等
如有任何帮助,我将不胜感激。
我试过简单地转储列表和元组,但它根本不起作用 - 这不是 Python 错误,而是逻辑错误。
import pickle
Currencies = "Pound-Sterling", "Euro", "US-Dollar", "Japanese-Yen"
Displayed = {}
Exchange_rates = pickle.load(open("rates.pkl","rb"))
print("This program allows you to check and change the currency conversion rates before using the converter program.")
for Line in Exchange_rates:
if not "Pound-Sterling" in Line:
Displayed_key = Line.split(" ")[0]
Displayed_value = Line.split(" ")[1]
Displayed[Displayed_key] = Displayed_value
print("£1 is", Line)
Exchange_rates = {}
New_rates = open("rates.pkl","wb")
pickle.dump("",New_rates)
pickle.dump("Pound-Sterling 1",New_rates)
if getYesNo("Do you want to change an exchange rate for a currency (Y/N):"):
for i in range(1,4):
Currency = Currencies[i]
print("£1 is", Currency, Displayed[Currency])
Prompt = "Please input the new rate for", Currency, ":"
Prompt = " ".join(Prompt)
New_rate = float(input(Prompt))
To_append = Currency, New_rate
pickle.dump(To_append,New_rates)
New_rates.close()
新的 pickle 文件应该在一行中以原始格式显示。相反,它要么在很多行上,要么不起作用,而且,我无法摆脱括号和逗号。
这是您的代码版本,其中有一些改进
改进:
- 我们不想担心关闭文件,所以我们使用
with open('Currencies.pkl', 'rb') as f:
。这称为上下文管理器,负责关闭文件。
- 我们要重用的代码已放入可调用函数中,例如
print_currencies
- 将
for i in range(1,4):
更改为 for currency in CURRENCIES:
既更具可读性又允许任意数量的货币。 CURRENCIES
这是一个字典,但可以是一个列表或任何可迭代对象。
- 我已经腌制了一个 python 字典对象来存储货币。
需要改进的地方:
- 我在代码中重复了'Currencies.pkl'
- 我不询问用户是否要关闭程序
- 如果我想保持货币不变怎么办?
import pickle
# I'll use this later to test if pickle file exists
import os.path
# let's use a default dictionary object
CURRENCIES = {
"Pound-Sterling": 1,
"Euro": 1,
"US-Dollar": 1,
"Japanese-Yen": 1
}
def load_currencies():
"""Load a dictionary object of currencies previously stored"""
with open('Currencies.pkl', 'rb') as f:
dict = pickle.load(f)
return dict
def dump_currencies(dict):
"""Dump a dictionary object of currencies"""
with open('Currencies.pkl', 'wb') as f:
pickle.dump(dict, f)
def print_currencies(dict):
for currency in dict:
if currency != "Pound-Sterling":
print("£1 is", dict[currency], currency)
# this is a special line of code that says "Hey if run me
# directly run this code but if you import me don't"
# - the code that runs effectively starts from here
if __name__ == '__main__':
# if our pickle file does not exist create it using the default
if not os.path.isfile('Currencies.pkl'):
dump_currencies(CURRENCIES)
print("This program allows you to check and change the currency conversion rates before using the converter program.")
CURRENCIES = load_currencies()
print_currencies(CURRENCIES)
answer = input("Do you want to change an exchange rate for a currency (Y/N):")
if answer == 'Y':
for currency in CURRENCIES:
# print(currency)
# print(type(currency)) <-- string
print("£1 is", CURRENCIES[currency], currency)
New_rate = float(input("Please input the new rate for "+currency+":"))
CURRENCIES[currency] = New_rate
dump_currencies(CURRENCIES)
我正在编写一个货币转换器,其中一个部分是一个程序,它允许您检查和更改英镑与其他三种货币之间的转换率。虽然实际转换很好,但我在将新汇率导出到单行 pickle 文件时遇到了问题。这是因为,费率以以下格式写入 pickle 文件中: 英镑兑 1 欧元 1.15 美元 1.3 等
如有任何帮助,我将不胜感激。
我试过简单地转储列表和元组,但它根本不起作用 - 这不是 Python 错误,而是逻辑错误。
import pickle
Currencies = "Pound-Sterling", "Euro", "US-Dollar", "Japanese-Yen"
Displayed = {}
Exchange_rates = pickle.load(open("rates.pkl","rb"))
print("This program allows you to check and change the currency conversion rates before using the converter program.")
for Line in Exchange_rates:
if not "Pound-Sterling" in Line:
Displayed_key = Line.split(" ")[0]
Displayed_value = Line.split(" ")[1]
Displayed[Displayed_key] = Displayed_value
print("£1 is", Line)
Exchange_rates = {}
New_rates = open("rates.pkl","wb")
pickle.dump("",New_rates)
pickle.dump("Pound-Sterling 1",New_rates)
if getYesNo("Do you want to change an exchange rate for a currency (Y/N):"):
for i in range(1,4):
Currency = Currencies[i]
print("£1 is", Currency, Displayed[Currency])
Prompt = "Please input the new rate for", Currency, ":"
Prompt = " ".join(Prompt)
New_rate = float(input(Prompt))
To_append = Currency, New_rate
pickle.dump(To_append,New_rates)
New_rates.close()
新的 pickle 文件应该在一行中以原始格式显示。相反,它要么在很多行上,要么不起作用,而且,我无法摆脱括号和逗号。
这是您的代码版本,其中有一些改进
改进:
- 我们不想担心关闭文件,所以我们使用
with open('Currencies.pkl', 'rb') as f:
。这称为上下文管理器,负责关闭文件。 - 我们要重用的代码已放入可调用函数中,例如
print_currencies
- 将
for i in range(1,4):
更改为for currency in CURRENCIES:
既更具可读性又允许任意数量的货币。CURRENCIES
这是一个字典,但可以是一个列表或任何可迭代对象。 - 我已经腌制了一个 python 字典对象来存储货币。
需要改进的地方:
- 我在代码中重复了'Currencies.pkl'
- 我不询问用户是否要关闭程序
- 如果我想保持货币不变怎么办?
import pickle
# I'll use this later to test if pickle file exists
import os.path
# let's use a default dictionary object
CURRENCIES = {
"Pound-Sterling": 1,
"Euro": 1,
"US-Dollar": 1,
"Japanese-Yen": 1
}
def load_currencies():
"""Load a dictionary object of currencies previously stored"""
with open('Currencies.pkl', 'rb') as f:
dict = pickle.load(f)
return dict
def dump_currencies(dict):
"""Dump a dictionary object of currencies"""
with open('Currencies.pkl', 'wb') as f:
pickle.dump(dict, f)
def print_currencies(dict):
for currency in dict:
if currency != "Pound-Sterling":
print("£1 is", dict[currency], currency)
# this is a special line of code that says "Hey if run me
# directly run this code but if you import me don't"
# - the code that runs effectively starts from here
if __name__ == '__main__':
# if our pickle file does not exist create it using the default
if not os.path.isfile('Currencies.pkl'):
dump_currencies(CURRENCIES)
print("This program allows you to check and change the currency conversion rates before using the converter program.")
CURRENCIES = load_currencies()
print_currencies(CURRENCIES)
answer = input("Do you want to change an exchange rate for a currency (Y/N):")
if answer == 'Y':
for currency in CURRENCIES:
# print(currency)
# print(type(currency)) <-- string
print("£1 is", CURRENCIES[currency], currency)
New_rate = float(input("Please input the new rate for "+currency+":"))
CURRENCIES[currency] = New_rate
dump_currencies(CURRENCIES)