[英]Finding desired search result from list in Txt file with python
def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
我的目標是創建自己的字典,但我在 txt 文件中添加了一個列表,所以它像這樣添加到 txt 文件中
words = {'araba:kol',
但是當我搜索 txt 文件時,它給了我整個列表
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
我該怎么做才能使它像這樣 output
car:araba
使用 JSON 模塊避免不得不自己逐行編寫字典。
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 現在是您寫入文件的數據。 請注意,您應該將 a+ 更改為 'w',因為每個文件只有一個字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.