2013-07-10 25 views
5

所以我有這個類叫Person,基本上有構造函數的名稱,ID,年齡,位置,目的地,我想要做的是,當我想做一個新人,我希望它從一個txt文件打開。從txt調用定義的東西... Python

例如,這是我的Person類(在模塊中,人)

class Person : 
    def __init__(self, name, ID, age, location, destination): 
     self.name = name 
     self.ID = ID 
     self.age = age 
     self.location = location 
     self.destination = destination 

    def introduce_myself(self): 
     print("Hi, my name is " + self.name + " , my ID number is " + str(self.ID) + " I am " + str(self.age) + " years old") 

import People 

Fred = People.Person("Fred", 12323, 13, "New York", "Ithaca") 

Fred.introduce_myself() 

所以基本上,而不是我不必手動鍵入初始化器「弗雷德,12232」等。 我想它從擁有的所有已寫在東西一個txt文件中讀取。

這是txt文件將在它

[Name, ID, Age, Location, Destination] 
[Rohan, 111111, 28, Ithaca, New Caanan] 
[Oat, 111112, 20, Ithaca, New York City] 
[Darius, 111113, 12, Los Angeles, Ithaca] 
[Nick, 111114, 26, New Caanan, Ithaca] 
[Andrew, 111115, 46, Los Angeles, Ithaca] 
[James, 111116, 34, New Caanan, Ithaca] 
[Jennifer, 111117, 56, Los Angeles, New Caanan] 
[Angela, 111118, 22, New York City, Los Angeles] 
[Arista, 111119, 66, New Caanan, Los Angeles] 
+0

確保只使用'file_handle.read()'和'str.split' –

回答

1
instances = {}   #use a dictionary to store the instances 

#open the file using `with` statement, it'll automatically close the 
#file for you 
with open('abc') as f: 
    next(f)     #skip header 
    for line in f:   #now iterate over the file line by line   
     data = line.strip('[]').split(', ') #strip [] first and then split at ', ' 
     #for first line it'll return: 
      #['Rohan', '111111', '28', 'Ithaca', 'New Caanan'] , a list object 

     #Now we can use the first item of this list as the key 
     #and store the instance in the instances dict 
     #Note that if the names are not always unique then it's better to use ID as the 
     #key for the dict, i.e instances[data[1]] = Person(*data) 
     instances[data[0]] = Person(*data) # *data unpacks the data list into Person 

#Example: call Rohan's introduce_myself 
instances['Rohan'].introduce_myself() 

輸出:

Hi, my name is Rohan , my ID number is 111111 I am 28 years old 
+0

你能更詳細地解釋代碼嗎?我有點新來python。 – Panthy

+0

@Panthy我補充說明一些。 –

+0

對不起,只是更多的問題。什麼是*數據? – Panthy

1

有幾種方法要做到這一點,最簡單的方法是使用標準文件格式,例如csv或序列化,使用JSON。我發現有這樣的標準模塊。

csv

import csv 
with open('persons.csv', newline='') as f: 
    dialect = csv.Sniffer().sniff(f.read(1024)) 
    f.seek(0) 
    reader = csv.reader(f, dialect) 
    for row in reader: 
     This_Person = People.Person(*row) 
     This.introduce_myself() 

你的文件是persons.csv和含

Rohan, 111111, 28, Ithaca, New Caanan 
Oat, 111112, 20, Ithaca, New York City 
Darius, 111113, 12, Los Angeles, Ithaca 
Nick, 111114, 26, New Caanan, Ithaca 
Andrew, 111115, 46, Los Angeles, Ithaca 
James, 111116, 34, New Caanan, Ithaca 
Jennifer, 111117, 56, Los Angeles, New Caanan 
Angela, 111118, 22, New York City, Los Angeles 
Arista, 111119, 66, New Caanan, Los Angeles 
… 

正如你所看到的,它仍然是非常短的,即使使用功能強大的模塊的一個例子,所以,請不要爲了任何非平凡的項目而分裂線。相信我,我曾經走過同樣的道路,很難從中恢復過來。

0

利用splat運算符和一些字符串方法。文本文件轉換爲使用data = [list val for val in file.read().split('\n')]列出的名單,然後,您可以調用構造函數:

peopleList = [] 
for person in data: 
     people.append(Person(*person)) 

peopleList將包含從文本文件

創建。如果你想要的變量就被定義的人的人的名單通過名稱,您可以使用vars(),該字典包含所有本地變量。然後代碼將是:

for person in data: 
     vars()[str(person[0])]=Person(*person) 
+2

的'瓦爾()'技巧是可怕的。它爲各種惡意代碼注入打開了大門。詢問小鮑比桌子。 – 9000

2

我會使用一個JSON文件,是這樣的:

cat people.json 
[ 
["Rohan", 111111, 28, "Ithaca", "New Caanan"], 
["Oat", 111112, 20, "Ithaca", "New York City"] 
] 

代碼:

import json 
with open('people.json') as people_file: 
    for record in json.load(people_file): 
    person = Person(*record) # items match constructor args 
    person.introduce_myself() 
0

試試這個:

people = {} 
with open('file.txt', 'r') as f: 
    data = [ l[1:-2].split(',') for l in f ][1:] 
    for row in data: 
     people{row[0]} = Person(*row) 

people['Rohan'].introduce_myself() 
0

導入文本文件到列表

with open(yourtextfile.txt) as peopleList: 
    listOfPeople = peopleList.readlines() 

然後你可以根據其長度通過listOfPeople循環,並在每次進入運行功能。

雖然我會推薦將它製作成json文件,這樣可以更容易地對數據進行短語處理。

0

你可以用我閃亮的新記錄不tsv module爲「製表符分隔值」文件,您可以用得到:

pip install --user tsv 

然後,讓與分離所有領域的製表符(不是空格)的文件,並在信息註釋行前的#:

# People file 
# Name ID Age Location Destination 
Mary 10 45 Hither Yon 
Bob 11 22 Here There 

(從這裏複製粘貼將無法工作; StackOverflow的替代選項卡中有空格的答案)

然後,像讀它:

import tsv 
import People 

for parts in tsv.TsvReader(open("people.txt")): 
    # This gets run with "parts" holding a list of all the parts on each line. 
    # If we don't care about having strings for ID and Age, we can just pass the 
    # whle thing as the arguments to Person's __init__ by "dereferencing" the 
    # list. See <http://stackoverflow.com/a/2921893/402891> 

    People.Person(*parts).introduce_myself() 

    # If you do care about type, it's a bit more complicated: 
    People.Person(parts[0], int(parts[1]), int(parts[2]), parts[3], 
     parts[4]).introduce_myself() 
    # You might want to define some intermediate variables here for the sake of 
    # good style. 
+0

'csv'模塊也可以處理'tsv'文件。或任何分隔符的sv文件。你爲什麼要另一個模塊? – Evpok

+0

'tsv'支持註釋,並且具有更簡單的API。另外,我還有一個模塊在學校任務中​​,我想我會把它上傳到PyPI。 – interfect