用逗号分割文件

时间:2017-05-26 08:57:21

标签: python list file split

我有一个python任务,需要我做以下事情,

*创建一个程序:*

  1. 按姓氏搜索此数据文件以检索并显示联系人的详细信息
  2. 按出生日期(dd / mm / yyyy)搜索此数据文件,以检索并显示所有具有特定月份生日的联系人
  3. 将新人详细信息添加到文件

    file = open ("c:\ABOOK.txt", "r")
    
    myfile = (file.readline())
    
    mywordlist = myfile.split()
    
    
    mylength= len(mywordlist)# reads how long it is
    print(mylength)
    count = 0 # counts 
    afound = 0 # counts 
    s_name = input("Enter a surname to be found:") 
    textfile=(file.readlines()) 
    print(textfile[0])
    mwl = textfile[0].split(",")
    mwl1 = textfile[1].split(",")
    mwl2 = textfile[2].split(",")
    mwl3 = textfile[3].split(",")
    mwl4 = textfile[4].split(",")
    while(count<len(textfile)):
        print(textfile[count])
        count = count + 1
    print(mwl,mwl1,mwl2,mwl3,mwl4)
    print(textfile.split(","))
    
  4. 文件被“,”打破了,这是记事本的摘录;它的六条线长。

    Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 
    135434,23/04/1973,sam.jackson@hotmail.com
    Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 
    678254,04/02/1965,the_man@btinternet.com
    Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 
    728443,19/02/1975,smorris@fgh.co.uk
    Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 
    288763,30/03/1960,harry.cobbly@somewhere.org.uk
    Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 
    276524,28/02/1980,jas.khan@hotmail.com
    Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 
    662554,04/04/1968,harriet.vickers@btinternet.com
    

2 个答案:

答案 0 :(得分:1)

以下是程序前两部分的基本解决方案,您可以对此进行大量改进,例如不对文件名进行硬编码,对新行字符进行条带化处理等。(如果您使用了这个确切的代码就会出现问题)不会得到100%)但我会把它作为一项任务给你:

import sys

def find_record_by_surname(input_surname):
    found = False
    with open("ABOOK.txt", "r") as f:
        for line in f:
            surname = line.split(',')[0]
            if surname == input_surname.title():
                found = True
    return found

def return_details_by_surname(input_surname):
    details = []
    with open("ABOOK.txt", "r") as f:
        for line in f:
            details = line.split(',')
            if details[0] == input_surname.title():
                break
    return details

def find_record_by_month_of_birth(input_month):
    if len(input_month) != 2:
        input_month = "0" + input_month
    found = False
    with open("ABOOK.txt", "r") as f:
        for line in f:
            month = line.split(',')[6].split('/')[1]
            if input_month == month:
                found = True
                break
    return found

def return_details_by_month_of_birth(input_month):
    if len(input_month) != 2:
        input_month = "0" + input_month
    details = ""
    with open("ABOOK.txt", "r") as f:
        for line in f:
            if line.split(',')[6].split('/')[1] == input_month:
                details = details + line
    return details

if __name__ == "__main__":
    print("Menu Choices")
    print("============")
    print("1: Search contacts by surname")
    print("2: Search contacts by month of birth")
    print("3: Add a new contact to ABOOK.txt")
    print("4: Exit")
    choice = input("Enter your choice: ")
    while choice != "4":
        if choice == "1":
            input_surname = input("Enter a surname you would like the records for from ABOOK.txt? ")
            if find_record_by_surname(input_surname):
                print("The record with the entered surname was found in ABOOK.txt")
                print("The details for that contact are:")
                print(return_details_by_surname(input_surname))
            else:
                print("The record with the entered surname was not found in ABOOK.txt")
        if choice == "2":
            input_month = input("Enter the month of birth (1-12) you would like the records for from ABOOK.txt? ")
            if find_record_by_month_of_birth(input_month):
                print("The details for the contact(s) with the entered month of birth are: ")
                print(return_details_by_month_of_birth(input_month))
            else:
                print("No record with the entered month of birth was found in ABOOK.txt")
        if choice == "3":
            # TO-DO code for adding a new contact
            print()
        print("Menu Choices")
        print("============")
        print("1: Search contacts by surname")
        print("2: Search contacts by month of birth")
        print("3: Add a new contact to ABOOK.txt")
        print("4: Exit")
        choice = input("Enter your choice: ")
    print("Goodbye!")    
    sys.exit(0)

使用的ABOOK.txt文件:

Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256135434,23/04/1973,sam.jackson@hotmail.com
Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196678254,04/02/1965,the_man@btinternet.com
Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256728443,19/02/1975,smorris@fgh.co.uk
Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458288763,30/03/1960,harry.cobbly@somewhere.org.uk
Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569276524,28/02/1980,jas.khan@hotmail.com
Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675662554,04/04/1968,harriet.vickers@btinternet.com

答案 1 :(得分:0)

要分割字符串,请使用

detail_arr = string.split(',')

detail_arr现在将是一个包含所有不同行的数组。

以下是代码中的示例:

>> str =  "Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256135434,23/04/1973,sam.jackson@hotmail.com"
>> str.split(',')
['Jackson', 'Samantha', '2 Heather Row', 'Basingstoke', 'RG21 3SD', '01256135434', '23/04/1973', 'sam.jackson@hotmail.com']

每个&gt;&gt;是在控制台中执行的一行。

为了添加细节,请将它们添加到您的arr中,然后执行:

str = ''.join(map(lambda x: x + ',', details_arr))[:-1]

Str现在将用逗号分隔你的所有数组,你可以把它写到你的文件中。

在你的代码中,你不想像第3行那样用空格分割数据,而是用逗号分隔。

你也有一段时间没有退出条款,所以你会陷入无限循环。

您的代码应如下所示:

file = open ("c:\ABOOK.txt", "r")

data = file.read()

data_rows = data.split(',') //every 8th row it will start a new entry (7,15,23...)

现在,按姓氏搜索将在第0,7,15行搜索... 按生日进行搜索将在第6,14,22行进行搜索。 你可以计算出所有的行。您可以创建一个计数器来查看您正在查看的联系人:

c = 0 //counter of entry
for i in xrange(len(data_rows)/8):
    if data_rows[i+row_number] == val: // row_number depends on what youre trying to match
        print ''.join(data_rows[c:c+8])
    c += 1

现在您可以判断哪个条目符合该值。

相关问题