使用python从Txt文件中的列表中查找所需的搜索结果


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()

我能做些什么让它像这个一样输出

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",因为每个文件只有一个字典。

最新更新