2014-11-15 3 views
0

저는 파이썬에서 CSV 파일의 데이터를 액세스, 검색 및 입력 (추가) 할 수있는 프로그램을 만들려고했습니다. 파일을 추가하고 인쇄 할 수 있지만 외부 파일을 검색하는 데 문제가 있습니다. 난 그냥 이름하여 파일에서 학생을 검색 할 수 있음을 나의 def s(): 지금 할 모르겠어요.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() 

:

이 내 코드는 지금까지 모습입니다 , 번호 또는 교사 그룹.

누구에게 아이디어가 있습니까?

로트

+1

: 파일의 각 행에 대해 행에 원하는 문자열이 포함되어 있는지 확인하십시오. 그렇다면 해당 행을 표시하십시오. 그렇지 않으면 다음 단계로 진행합니다. –

+0

감사합니다. 나는 당신이 말하는 것을 이해하고 있다고 생각합니다. @ 폴 콜링우드 – Lotz

답변

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 작성자 방법을 사용하여 데이터를 CSV 파일로 작성해야합니다. 를 CSV를 읽는 동안 우리가 키워드에 을 사용하여 모든 요소를 ​​검색 할 수있는 목록을 제공으로

검색이 용이하다.

0

레코드 세트를 통해 검색하는 것은 간단한 문제는 아닙니다. 당신이 (빠른 검색을 위해 그 정보를 복사하는 데이터 구조)에 검색하고자하는 각 필드에 대한

  1. 지수 :이이 같은 슈퍼 복잡하지 않습니다하지만 당신은 일의 몇 필요합니다 희망 어쩌면 사용자를 컴파일하여 시작 : 사용자 이름, 교사 그룹 또는 번호를 입력 여부를 추측 (또는 그들에 의해 검색 할 무엇을 물어)

당신은 여기에 자신의 물건을 만들 수의

  • 영리한 방법 '정규 표현식에 입력하고 항목과 사용자의 que 사이에서 이진 비교를 수행하여 CSV 파일의 하위 집합 검색 (이름 열과 같은) 너.

    인덱스를 만들 수도 있습니다. 데이터 유형을 선택하거나 (물론 자신 만의 인덱스로 만들 수 있습니다) 레코드의 수에 대해 합리적인 시간 내에 자신을 검사하는 것이 효율적입니다 가능한 한 시간 복잡성).

    많은 사람들이이 문제에 대해 오랫동안 노력해 왔으며 많은 도움을 드릴 수있는 많은 코드를 가지고 있습니다. Information Retrieval을 확인하고보고있는 문제 유형에 대한 느낌을 확인하십시오.

    검색에는 Xapian과 같은 것을 사용할 수 있지만 대안이 많이 있습니다.여기

    당신을 도울 수있는 몇 가지 SO 질문들 : 선택한 answer없이 하나의 any 기능을 사용하는 한, 그리고 columns

  • 1

    에 적절한 모양을 얻기에 대한 하나 csv에 DictReader가있다 모듈은 당신이 원하는에 대 한 완벽

    는 정보를 원하시면 난 당신의 코드에서 몇 가지 문제를 참조하십시오 (아마도 student_num 같은 일부 필드는 고유 한 가정) 수행하는

    1. 필요하지 않다면 함수에서 모듈을 가져 오지 말고 반복하지 말고 그냥 함수 밖의 맨 위에 하나의 import 문을 넣고 가져 오면 가져 오십시오;)
    2. 함수의 함수 사용 대신 파일 이름을 체내 상수 리터럴을 harcoding의 매개 변수는
    3. 이`: 파일을 열고 닫는 그 전에 작업 할 할 때 student_num+","+name+","+tutor_group+","+gender 제거해야합니다, ', '.join(your_iterable) 대신
    4. 를 사용, 상황에 맞는 관리자를 사용하여 open ('myfile.txt') with flux : ', 파일이 열리는 블록을 정의하고 문제가 발생하고 예외가 발생해도 파일이 자동으로 닫힙니다.