我有一个使用itertools的文本文件字典。
import itertools
plantfile = 'myplants.txt' #file path
plant = {} #create an empty dictionary
with open(plantfile, 'r') as f:
for empty_line, group in itertools.groupby(f, lambda x: x == '\n'):
if empty_line:
continue
fruit, *desc = map(str.strip, group)
plant[fruit] = desc
结果是:
{'banana' : ['delicious', 'yellow'],
'watermelon' : ['big', 'red'],
'orange' : ['juicy', 'vitamin c']}
我想提示用户水果(键)的名称以同时修改键和描述(值)或删除整个记录。如果可以使用def()函数,那将是最好的。
以下是我当前的代码。它们不会向我返回任何错误消息,但是,它们也不会反映在字典文件中。
print("What do you want to do with this database?
1. Modify fruit information
2. Delete fruit record")
choice == input("Please enter your choice in number: ")
while True:
try:
if choice == '1':
original_name = input("What is the fruit name you would like to modify?").upper()
new_name = input("What is the new fruit name?")
with open(file, 'r+') as f:
string = f.read()
string = string.replace(original_name, new_name)
f.truncate(0)
f.seek(0)
f.write(string) #writeback to file
print(f"You have modified {original_name} to {new_name}.")
break
else:
delname = input("Please enter the name of the fruit: \n").upper()
delname = dict(filter(lambda item: delname in item[0], plant.items()))
break
except ValueError:
print("Invalid input. Please try again.")
我不知道如何修改值,并且上述修改键名的代码似乎也不起作用。
上面删除整个记录的代码也没有反映在原始文件中。
例如,我想将西瓜的价值从“大”更改为“硬”,并希望删除整个香蕉记录。
{'watermelon' : ['hard', 'red'],
'orange' : ['juicy', 'vitamin c']}
请帮帮我。谢谢
答案 0 :(得分:1)
此解决方案适用于编辑之前的问题。先前进行的.upper()
输入中有一个original_name
。修改后的代码如下:
import itertools
file = 'file.txt'
plant = {}
with open(file, 'r') as f:
for empty_line, group in itertools.groupby(f, lambda x: x == '\n'):
if empty_line:
continue
fruit, *desc = map(str.strip, group)
plant[fruit] = desc
print(plant)
original_name = input("What is the fruit name you would like to modify?")
new_name = input("What is the new fruit name?")
with open(file, 'r+') as f:
string = f.read()
string = string.replace(original_name, new_name)
f.seek(0)
f.write(string) #writeback to file
print(f"You have modified {original_name} to {new_name}.")
假设您的file.txt
如下所示:
banana
delicious, yellow
watermelon
big, red
orange
juicy, vitamin cc