1

我正在自学 python 并想学习如何搜索文本文件。例如,我有一个长长的全名和地址列表,并且希望能够输入名字,然后打印与该名称对应的详细信息。解决此问题的最佳方法是什么?谢谢!

我拥有的数据位于 .txt 文件中的列中,如下所示:

Doe, John        London
Doe, Jane        Paris
4

4 回答 4

1

如果您设计了数据格式,那么固定宽度的列就不是一个很好的格式。但如果你被他们困住,他们很容易处理。

首先,您要解析数据:

addressbook = []
with open('addressbook.txt', 'r') as f:
    for line in f:
        name, city = line[:17], line[17:]
        last, first = name.split(',')
        addressbook.append((first, last, city))

但是现在,您希望能够按名字进行搜索。你可以这样做,但是对于一个巨大的地址簿来说可能会很慢,而且代码不会很直接:

def printDetails(addressbook, firstname):
    for (first, last, city) in addressbook:
        if first == firstname:
            print fist, last, city

如果我们不只是使用元组列表,而是使用字典,将名字映射到另一个字段怎么办?

addressbook = {}
with open('addressbook.txt', 'r') as f:
    for line in f:
        name, city = line[:17], line[17:]
        last, first = name.split(',')
        addressbook[first]=((last, city))

但这不好——每个新的“John”都会删除任何以前的“John”。所以我们真正想要的是一个字典,将名字映射到元组列表

addressbook = collections.defaultdict(list)

with open('addressbook.txt', 'r') as f:
    for line in f:
        name, city = line[:17], line[17:]
        last, first = name.split(',')
        addressbook[first].append((last, city))

现在,如果我想查看该名字的详细信息:

def printDetails(addressbook, firstname):
    for (last, city) in addressbook[firstname]:
        print firstname, last, city

无论您采用哪种方式,都有一些明显的地方可以改进这一点。例如,您可能会注意到某些字段的开头或结尾有多余的空格。你将如何摆脱那些?如果你调用printDetails“Joe”而没有“Joe”,你将一无所获;也许一个很好的错误信息会更好。但是,一旦您掌握了基础知识,您以后可以随时添加更多内容。

于 2012-12-12T22:44:54.123 回答
1

我会明智地使用该split命令。当然,这取决于您的文件的分隔方式,但您的示例显示分隔数据字段的字符是空格。

对于文件中的每一行,执行以下操作:

last, first, city = [data.strip(',') for data in line.split(' ') if data]

然后根据这些属性进行比较。

显然,如果您的数据字段中有空格,这将中断,因此在您采用这样的简单方法之前,请确保不是这种情况。

于 2012-12-12T22:45:25.307 回答
0

你可以做这样简单的事情:

name = raw_input('Type in a first name: ')  # name to search for

with open('x.txt', 'r') as f:  # 'r' means we only intend to read
    for s in f:
        if s.split()[1] == name:  # s.split()[1] will return the first name
            print s
            break  # end the loop once we've found a match
    else:
        print 'Name not found.'  # this will be executed if no match is found
输入名字:
能源部,简巴黎

相关文件

于 2012-12-12T22:43:15.760 回答
0

要在 python 中读取文本文件,您可以执行以下操作:

f = open('yourtextfile.txt')
for line in f:
    //The for-loop will loop thru the whole file line by line
    //Now you can do what you want to the line, in your example
    //You want to extract the first and last name and the city
于 2012-12-12T22:45:45.900 回答