2016-12-23 29 views
-2

有沒有辦法將.txt文件轉換爲列表,並將列表一次保存到變量中? 例如: 如果.txt文件看起來是這樣的:將.txt文件轉換爲python中的變量

Blue,color,sky 
Red,color,blood 
Dog,animal,bark 

我怎麼把它存爲

Things = {Blue,Red,Dog} 
Types = {color,animal} 
Related = {sky,blood,bark} 

感謝您的幫助..

+1

閱讀文件,將其解析爲單個標記(藍色,狗,動物等),然後將其分配給一個變量。你有什麼嘗試? – Carcigenicate

+2

這裏沒有特別的方法。但是你可以把它保存爲'JSON'或'YAML'(或'Pickle'),然後它會更容易。 – furas

+0

你有'CSV'格式的數據,所以你可以嘗試'csv'模塊或者更簡單的'pandas'模塊。 – furas

回答

4

通過文字去,剝離每行並將其拆分爲',',將其解壓縮並將其發送到zip,mapset,然後解壓縮該作業。

>>> text = '''Blue,color,sky 
... Red,color,blood 
... Dog,animal,bark'''.splitlines() # text can also be a file object 
>>> things, types, related = map(set, zip(*(i.strip().split(',') for i in text))) 
>>> things 
{'Dog', 'Blue', 'Red'} 
>>> types 
{'color', 'animal'} 
>>> related 
{'blood', 'bark', 'sky'} 
+0

偉大的答案,但只是爲了保持與OP清楚的事情,如何打開一個文件的例子? – tdelaney

+1

@tdelaney - 它只是與'open('file.txt')一起作爲文本:',在任何教程中都有介紹。 – TigerhawkT3

0

您在CSV格式有數據,所以你可以使用pandas
(但也許正是因爲這個小問題過於強大的模塊)

import pandas as pd 

df = pd.read_csv(filename, names=['Things', 'Types', 'Related']) 

,然後你可以使用

things = set(df['Things']) 
types = set(df['Types']) 
related = set(df['Related']) 

完整的工作示例使用StringIO創建模擬真實文件的文件類對象。

import pandas as pd 

import io 

data = '''Blue,color,sky 
Red,color,blood 
Dog,animal,bark''' 

f = io.StringIO(data) 

df = pd.read_csv(f, names=['Things', 'Types', 'Related']) 

print(df) 

things = set(df['Things']) 
types = set(df['Types']) 
related = set(df['Related']) 

print(things) 
print(types) 
print(related) 

結果

Things Types Related 
0 Blue color  sky 
1 Red color blood 
2 Dog animal bark 

{'Blue', 'Red', 'Dog'} 
{'animal', 'color'} 
{'bark', 'sky', 'blood'} 
0

定義列表保存接收到的值的東西,相關的和類型

accepted_things = ["Blue", "Red", "Dog"] 
accepted_related = ["Sky", "Blood", "Bark"] 

things = [] 
related = [] 
//Same for Types 

with open(file_path, "r") as file : 
     for line in file : 
      results = line.split(",") 
      //Open file, loop through each line and separate values with comma 
      for i in results 
       if i in accepted_things : 
        things.append(i) 
       elif i in accepted_related : 
        related.append(i) 

也許不是最完美的解決方案,但把工作做到完美。

相關問題