从用户inpu读取文件中的数据

2024-10-02 22:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个文本文件,我用一个人的名字,后跟一个逗号,然后是他们可以居住的地方。是的,我知道这是随机的,但我需要一种方法来理解:)

这是一个文本文件namesAndPlaces.txt文件“”:

鲍勃,曼谷
埃莉,伦敦
安东尼,北京
迈克尔,波士顿
德克萨斯州弗雷德
加利福尼亚州艾莉莎

因此,我希望用户能够在程序中输入一个名称,然后程序查看文本文件以查看他们的居住地,然后将其打印给用户。你知道吗

我该怎么做? 谢谢 迈克尔


Tags: 文件方法用户程序txt名称地方名字
2条回答

阿内塔建议用一种更像Python的方式来做同样的事情

with open(filename, 'r') as source:
    text = source.read()
    place_to_names = dict([line.split(r',') for line in text.split()])

while True:
    name = raw_input('Enter a name:')
    print("%s lives in %s" % (name, places_to_names[name]))

我会这样做:

text_file = open('pathtoFile', 'r').read()
text = text_file.split()

#turn the text into a dictionary
names_dic = []
for x in text:
    x = x.split(',')
    names_dic.append(x)

names_dic = dict(names_dic)

print names_dic  #for testing

# asking a user to enter a name
name = "not_in_dic"
while name not in names_dic:
    name = raw_input("Enter the name? ")
    print name, "lives in ", names_dic[name]

相关问题 更多 >