3 回答

TA贡献1820条经验 获得超10个赞
import csv
def get_data(filename):
with open(filename) as f:
reader = csv.DictReader(f, delimiter=',')
data = {row['truecode']: row for row in reader}
return data
def main():
filename = 'results.txt'
data = get_data(filename)
code = input('Enter code: ')
try:
info = data[code]
print("Your villager is " + info['villagername'])
print("They are a " + info['personality'] +
" type villagers and of the " + info['species'] + " species.")
print("Their birthday is " +
info['birthday'] + " and they are a " + info['zodiac'])
print("I hope you enjoyed this quiz!")
except KeyError:
print('Invalid code')
if __name__ == "__main__":
main()

TA贡献1803条经验 获得超3个赞
import csv
def compare_codes(true_code):
with open(''file.txt) as csvfile:
details_dict = csv.reader(csvfile)
for i in details_dict:
if i['truecode'] == tru_code:
print("Your villager is:",i['villagername'])
print("They are a " + i['personality'] + " type villagers and of the " + i['species'] + " species.")
print("Their birthday is " + i['birthday'] + " and they are a " + i['zodiac'])
print("I hope you enjoyed this quiz!")
break
compare_codes('A420')
上面的代码读取文本文件并将输入与文件中的 truecode 值进行比较并显示信息。

TA贡献1876条经验 获得超5个赞
您拥有的文件类型实际上称为 CSV 文件。如果愿意,您可以使用任何电子表格程序打开您的文本文件,您的数据将显示在相应的单元格中。使用csv 模块读取数据。
import csv
def get_quiz_results(truecode):
with open('your-text-file.txt') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
# row is a dictionary of all of the items in that row of your text file.
if row['truecode'] == truecode:
return row
然后打印出文本文件中的信息
truecode = 'A330'
info = get_quiz_results(truecode)
print("Your villager is " + info["villagername"])
print("They are a " + info["personality"] + " type villagers and of the " + info["species"] + " species.")
print("Their birthday is " + info["birthday"] + " and they are a " + info["zodiac"])
print("I hope you enjoyed this quiz!")
遍历文件时,csv 模块会将文件的每一行转换为使用逗号作为分隔符的字典。第一行很特殊,用于创建字典键。
添加回答
举报