Python 3.x 通过搜索关键字修改/删除文本文件字典中的值
我有一个使用itertools转换成字典的文本文件Python 3.x 通过搜索关键字修改/删除文本文件字典中的值,python-3.x,function,dictionary,key,key-value,Python 3.x,Function,Dictionary,Key,Key Value,我有一个使用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:
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']}
请帮帮我。感谢您更新本节以反映以下内容:
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?").upper() #convert this to uppercase also
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
f.close() # TODO: You have not been saving the file record. Implement this.
print(f"You have modified {original_name} to {new_name}.")
break
else:
delname = input("Please enter the name of the fruit: \n").upper()
with open(file, 'r+') as f:
f.read()
f.pop(delname, None) #This deletes or lets you go ahead if it doesnt exist
f.close()
print(f"You have deleted {delname}.")
break
except ValueError:
print("Invalid input. Please try again.")