3 回答

TA貢獻1820條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超5個贊
您擁有的文件類型實際上稱為 CSV 文件。如果愿意,您可以使用任何電子表格程序打開您的文本文件,您的數(shù)據(jù)將顯示在相應(yīng)的單元格中。使用csv 模塊讀取數(shù)據(jù)。
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 模塊會將文件的每一行轉(zhuǎn)換為使用逗號作為分隔符的字典。第一行很特殊,用于創(chuàng)建字典鍵。
添加回答
舉報