【问题标题】:Searching a .CSV file搜索 .CSV 文件
【发布时间】:2014-11-15 14:10:01
【问题描述】:

我一直在尝试在 python 中创建一个程序,您可以在其中访问、搜索和输入(附加)CSV 文件中的数据。我可以附加和打印文件,但是在搜索外部文件时遇到了麻烦。

这是我的代码到目前为止的样子:

def a():
    # knows to use the file (getting something that's made)
    import csv

    myfile = open("student01.csv", "a")

    student_num = input("Enter the student number: ")
    name = input("Enter student's name: ")
    tutor_group = input("Enter the tutor group: ")
    gender = input("Enter M or F: ")

    new_record =student_num+","+name+","+tutor_group+","+gender

    myfile.write(str(new_record))
    myfile.write("\n")

    myfile.close()

def d():
    # knows to use the file (getting something that's made)
    import csv

    myfile = open("student01.csv", "rb")
    reader = csv.reader(myfile)
    for row in myfile:
        print(row)

    myfile.close()

def menu():
    print("Welcome to Student.csv\nWhat would you like to do?")
    print()
    print("1. Add to the file")
    print("2. Display all the data from the file")
    print("3. Search for particular data")
    enter = input("Enter 1, 2 or 3: ")
    enter = enter.upper()
    if enter == "1":
        a()
    elif enter == "2":
        d()
   else:
        s()

    menu()

我只是不知道现在要为我的def s(): 做什么,以便我能够在文件中按姓名、编号或导师组搜索学生。

有人有什么想法吗?

洛兹

【问题讨论】:

  • 类似:对于文件中的每一行,检查行是否包含所需的字符串。如果是这样,则显示该行。如果没有继续下一个。
  • 谢谢,我想我明白你在说什么。 @PaulCollingwood

标签: python csv external


【解决方案1】:
import csv

def create_record(number_of_students):

    while number_of_students:
        student_num = raw_input("Enter the student number: ")
        name = raw_input("Enter student's name: ")
        tutor_group = raw_input("Enter the tutor group: ")
        gender = raw_input("Enter M or F: ")

        if student_num and name and tutor_group and gender:
            record_list = [student_num, name, tutor_group, gender]

            with open("student_record.csv", "ab") as wf:
                 writer = csv.writer(wf)
                 writer.writerow(record_list)
        number_of_students -= 1

def display_record(option):

    with open("student_record.csv", "r") as rf:
        reader = csv.reader(rf)
        if option == 2:
            for row in reader:
                print "  ".join(row)
        elif option == 3:
            search_feild = raw_input("Search by student name, number, tutor_group, gender :")
            for row in reader:
                if search_feild in row:
                    print "  ".join(row)


def main():
    print("1. Add to the file")
    print("2. Display all the data from the file")
    print("3. Search for particular data")
    print("0. To Exit")

    choice = True
    while choice:
        your_choice = input("Enter your choice:")
        if your_choice == 1:
            number_of_students = input("Enter number of records you want to enter:")    
            create_record(number_of_students)
        if your_choice == 2:
            display_record(2)
        if your_choice == 3:
            display_record(3)
        if your_choice == 0:
            choice = False

if __name__ == "__main__":
    main()    

Output:
1. Add to the file
2. Display all the data from the file
3. Search for particular data
0. To Exit
Enter your choice:1
Enter number of records you want to enter:3
Enter the student number: 1
Enter student's name: Jhon
Enter the tutor group: Python
Enter M or F: M
Enter the student number: 2
Enter student's name: Lina
Enter the tutor group: Django
Enter M or F: F
Enter the student number: 3
Enter student's name: Max
Enter the tutor group: Python
Enter M or F: M
Enter your choice:2
1  Jhon  Python  M
2  Lina  Django  F
3  Max  Python  M
Enter your choice:3
Search by student name, number, tutor_group, gender :Python
1  Jhon  Python  M
3  Max  Python  M
Enter your choice:3
Search by student name, number, tutor_group, gender :F
2  Lina  Django  F
Enter your choice:0

您甚至应该使用 csv writer 方法将数据写入 csv 文件。

搜索很容易,因为在读取 csv 时,它会提供一个 list,我们可以在其中使用 in 关键字搜索任何元素。

【讨论】:

    【解决方案2】:

    csv 模块中有一个 DictReader,非常适合您想做的事情(假设某些字段是唯一的,可能是 student_num)

    仅供参考,我在您的代码中发现了一些问题

    1. 非必要时不要在函数中导入模块,也不要重复自己(DRY),只需在任何函数之外的顶部放置一个import语句,如果你导入了一些东西,就使用它;)李>
    2. 使用函数的参数而不是在正文中对文件名常量进行编码
    3. this : student_num+","+name+","+tutor_group+","+gender 应该被删除,改用 ', '.join(your_iterable)
    4. 当您想要打开一个文件并在关闭它之前对其进行处理时,请使用上下文管理器:`with open('myfile.txt') as Flux:',它定义了打开文件的块,即使出现问题并引发异常,文件也会自动关闭

    【讨论】:

      【解决方案3】:

      搜索一组记录并不是一个简单的问题。我希望这不会让您的喜好变得超级复杂,但您需要做一些事情:

      1. 您要搜索的每个字段的索引(一种复制信息以便快速查找的数据结构)
      2. 一种猜测用户是否输入姓名、导师组或号码(或者只是询问他们想要搜索的内容)的巧妙方法

      您可以在这里制作自己的东西:也许首先将用户的输入编译为正则表达式,然后通过在条目和用户查询之间进行二进制比较来搜索 CSV 文件的子集(如名称列)。

      您还可以创建索引:只需选择一种数据类型(当然也可以自己创建),并确保它能够在合理的时间内非常高效地检查您拥有的记录数量(尽可能低时间复杂度尽可能)。

      再说一次,很多人已经在这个问题上工作了很长时间,并且有大量的代码可以帮助您。查看Information Retrieval,了解您正在查看的问题类型。

      您可以使用 Xapian 之类的内容进行搜索,但有很多替代方法。

      以下是一些可能对您有所帮助的 SO 问题:没有选择 answer 的问题,使用 any 函数的问题,以及关于正确查看 columns 的问题

      【讨论】:

        猜你喜欢
        • 2022-01-15
        • 2011-08-30
        • 1970-01-01
        • 2021-10-13
        • 2014-02-25
        • 2022-01-07
        • 2014-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多