有没有办法将.txt文件转换为列表,+一次将列表保存到变量中? 例如 : 如果.txt文件如下所示:
Blue,color,sky
Red,color,blood
Dog,animal,bark
如何将其另存为
Things = {Blue,Red,Dog}
Types = {color,animal}
Related = {sky,blood,bark}
感谢您的帮助..
答案 0 :(得分:4)
浏览文字,删除每一行并将其拆分为void doStuff(T)(bool param) /*if T is a Throwable*/ {
// do stuff...
}
,将其解压缩并发送至','
,将zip
发送至map
,然后解压缩作业
set
答案 1 :(得分: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'}
答案 2 :(得分: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)
也许不是最优雅的解决方案,但会完美地完成工作。